
.
I have 4 tables as shown above. Now I’m trying to get all the data including article subjects, tags for each article, and number of comments for each article, in ONE query.
The sql query I’m using now is
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
The result: data in [ ] is what I actually get
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
)
)
For the real situation here in my application, number of tags and number of comments will multiply with each other. For example: if there are 4 comments, and 3 tags in one article, my query will result in
tags: html,css,php, html,css,php, html,css,php, html,css,php (instead of html,css,php)
comments: 12 (instead of 4)
I know there must be something wrong with my query statement, I just don’t know how to fix it.
Someone please help. Thanks.
I think you need a nested query to count the comments