gpt4 book ai didi

php - 如何从两个表中获取特定数据?

转载 作者:行者123 更新时间:2023-11-29 20:49:30 25 4
gpt4 key购买 nike

我有下表
评论表:

id  user_id question_id comment 
1 2 3 hii

用户表:

id    u_name   user_image 
2 naveen a.jpg

当选择 Question_id=3 时,如何打印如下值:

user_image     u_name    comment
a.jpg naveen hii <br>

sql查询:

$sql = "SELECT u.user_image, u.name, c.comment
FROM users u INNER JOIN comment c
ON u.id = c.user_id
WHERE c.question_id = 2";

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($rows = mysqli_fetch_assoc($result)) {
echo '<td class="small">'.$rows['name'].'</td>';
echo '<td class="small">'.$rows['user_image'].'</td>';
echo '<td class="small">'.$rows['comment'].'</td>';

}
}
else {
echo "0 results";
}

最佳答案

使用INNER JOIN:

SELECT u.user_image, u.u_name, c.comment
FROM users u INNER JOIN comments c
ON u.id = c.user_id
WHERE c.question_id = 3

SQLFiddle

关于php - 如何从两个表中获取特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38176397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com