
。
如上文所示,我有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)
评论: 12 (而不是4)
我知道我的查询语句一定有问题,我只是不知道如何修复它。谁来帮帮忙。谢谢。
发布于 2012-09-18 17:03:51
我认为您需要一个嵌套查询来计算注释。
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发布于 2012-09-18 17:01:56
在公共列上将表连接在一起时,将得到共享这些列的所有行组合。
在本例中,对于aid 2,文章中有1行,注释中有2行,关系中有2行。1*2*2 = 4,这是COUNT()函数的结果。
如果要运行此查询:
SELECT * 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
WHERE articles.aid = 2您将能够看到COUNT正在计算的四个生成的行。
aid | subject | cid | comment | tid | name
----+---------+-----+----------+-----+------
2 | bar | 1 | comment1 | 1 | html
2 | bar | 1 | comment1 | 3 | mysql
2 | bar | 2 | comment2 | 1 | html
2 | bar | 2 | comment2 | 3 | mysql如果您只想计数注释的数量,您可以将查询中的COUNT(comments.aid)更改为COUNT(DISTINCT comments.cid) --这将在它进行计数时将重复的内容排除在外。
https://stackoverflow.com/questions/12481381
复制相似问题