.
我有 4 个表,如上所示。现在,我试图在 ONE 查询中获取所有数据,包括文章主题、每篇文章的标签以及每篇文章的评论数。
我现在使用的sql查询是
SELECT
articles.subject, GROUP_CONCAT(tags.name) AS tags, COUNT(comments.aid) AS comments
FROM articles
LEFT JOIN comments ON comments.aid = articles.aid
LEFT JOIN relations ON relations.aid = articles.aid
LEFT JOIN tags ON tags.tid = relations.tid
GROUP BY
articles.aid
结果:[]中的数据是我实际得到的
array
(
1 => array
(
subject => foo
tags =>
comments => 1
)
2 => array
(
subject => bar
tags => html,mysql [html,mysql,html,mysql]
comments => 2 [4]
)
3 => array
(
subject => baz
tags => php
comments => 0
)
)
对于我的应用程序中的真实情况,标签数量和评论数量会成倍增加。例如:如果一篇文章中有 4 条评论和 3 个标签,我的查询结果将是
标签:html、css、php、html、css、php、html、css、php、html、css、php(而不是 html、css、php)
评论:12(而不是 4)
我知道我的查询语句一定有问题,只是不知道如何修复它。 有人请帮忙。谢谢。
最佳答案
我认为你需要一个嵌套查询来计算评论数
SELECT
articles.subject, GROUP_CONCAT(tags.tag) AS tags, comments
FROM articles
LEFT JOIN (
select aid,count(cid) as comments from comments group by aid
) AS commentscount ON commentscount.aid = articles.aid
LEFT JOIN relations ON relations.aid = articles.aid
LEFT JOIN tags ON tags.tid = relations.tid
GROUP BY
articles.aid
关于mysql - 从查询中的 4 个连接表中获取数据 (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481381/