因此,只有当我调用的表与请求匹配时,此代码才有效,但是我仍然想显示主表(即新闻表)的所有值。解决这个问题的最佳方法是什么
这里我刚刚完成我的查询
$query="SELECT * FROM news n,category c, comments a, appusers u, admins w WHERE n.cat_id=c.category_id AND w.userId=n.post_author AND a.post_id=n.id AND u.user_id=a.userID ORDER BY a.commentid DESC, n.id DESC";
$result = mysql_query($query);
$json_response = array();
while($row=mysql_fetch_array($result)) {
if (!isset($json_response[ $row['id'] ])) {
$json_response[ $row['id'] ] = [
'id' => $row['id'],
'title' => $row['title'],
'catId' => $row['cat_id'],
'catName' => $row['category_name'],
'catImage' => $row['category_image'],
'postDate' => $row['post_date'],
'postImage' => $row['post_image'],
'post' => $row['post'],
'commentCount' => $row['comment_count'],
'videoUrl' => $row['video_url'],
'tags' => $row['tags'],
'author' => $row['tags'],
'comments' => [],
];
}
$json_response[ $row['id']]['comments'][] = [
'id' => $row['commentid'],
'comment' => $row['comment'],
'name' => $row['user_name'],
'userId' => $row['userID']
];
}
$data = [];
foreach ($json_response as $element) {
$data[] = $element;
}
echo json_encode($data, JSON_PRETTY_PRINT);
然后我尝试在此处显示 JSON 结果
最佳答案
请尝试以下查询,这可能适合您。
select * from news n
LEFT JOIN category c ON c.category_id = n.cat_id
LEFT JOIN admins w ON w.userId=n.post_author
LEFT JOIN comments a ON a.post_id=n.id
LEFT JOIN appusers u ON u.user_id=a.userID
ORDER BY
a.commentid DESC, n.id DESC";
关于php - 在 PHP 中 SELECT 多个表 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649140/