我有一个文章表,我在主页的while循环中显示它。在while循环中,我想显示每篇文章的评论数和图像数。
它现在对我有用,但它总共有三个查询,我试图在第一个查询中将它组合在一起,然后只在一个while循环中显示所有这些查询。以下是我想要实现的目标:Articles page
我正在遵循的当前格式:
//a represents articles table, c represents comments table, i represents image table
$query = mysqli_query($conn, "SELECT a.a_id, a.title, a.datetime, a.user_id FROM a ORDER BY a.datetime DESC");
while($fetch = mysqli_fetch_assoc($query){
$imageQ = msqli_query($conn, "SELECT COUNT(image_path), image_path FROM i WHERE a_id = '$fetch['a_id']'");
$imageFetch = mysqli_fetch_assoc($imageQ);
$commentQ = mysqli_query($conn, "SELECT COUNT(comment_id) FROM c WHERE a_id = '$fetch['a_id']'");
$commentFetch = mysqli_fetch_assoc($commentQ);
}
我想将所有这些查询塞进一个查询中,该查询获取每篇文章和第一张图片的文章和评论数量和图像数量。
答案 0 :(得分:0)
您可以使用类似
的mysql嵌套查询选择a。,tab1。,tab2。*从INNER JOIN(SELECT * FROM b)作为tab1 INNER JOIN(SELECT * FROM c)作为tab2
希望这可以让你得到理想的输出。
由于
答案 1 :(得分:0)
图像和注释是单独的维度。所以,你必须要小心如何将它们组合在一起。在您的情况下,您可以在执行连接之前聚合值:
SELECT a.a_id, a.title, a.datetime, a.user_id,
i.num_images, c.num_comments
FROM a LEFT JOIN
(SELECT a_id, COUNT(image_path) as num_images
FROM i
GROUP BY a_id
) i
ON i.a_id = a.a_id LEFT JOIN
(SELECT a_id, COUNT(comment_id) as num_comments
FROM c
GROUP BY a_id
) c
ON c.a_id = a.a_id
ORDER BY a.datetime DESC;