PHP:计算项目并回显它们

时间:2014-04-01 16:36:12

标签: php mysql

我有三张桌子: 表1:主题表

topic_id       name      date
1              blue         3/20/14
2              green        3/21/14
3              red          3/22/14

表2:回复表

reply_id      topic_id      message 
12            1             bla bla
13            1             bla bla
14            2             bla bla

表3:评论表

comment_id    topic_id      message
50            1             bla bla
51            2             bla bla

如您所见,表2和表3通过名为topic_id的外键与表1相关

我使用以下查询SELECT和ECHO数据如下:

$query ="SELECT name, COUNT(replies.topic_id) AS replies, COUNT(comments.topic_id) AS comments
         FROM topics
         LEFT JOIN replies
         ON topics.topic_id = replies.topic_id
         LEFT JOIN comments
         ON topics.topic_id = comments.topic_id";

$r = mysqli_query($dbc, $query);
if (mysqli_num_rows($r) > 0) {
   while ($num = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
      echo {$num['name']};
      echo {$num['replies']};
      echo {$num['comments']};
   }
}

如您所见,topic_id number 1

有两个回复和一个评论

然而,它输出两个回复和两个评论如下:

name       replies     comments
blue        2            2

正确的结果应该是2条回复和1条评论。

你能帮帮我吗?

由于

2 个答案:

答案 0 :(得分:1)

有帮助

select 
t.name, 
`replies`,
`comments`
from topics t
left join 
( 
    select topic_id,count(reply_id) as `replies`
    from replies
    group by topic_id
)r
on r.topic_id = t.topic_id
left join
(
    select topic_id,count(comment_id) as `comments`
    from comments
    group by topic_id
)c
on c.topic_id = t.topic_id
group by t.name

在此处查看演示http://www.sqlfiddle.com/#!2/1412f/7

答案 1 :(得分:0)

你可以试试

SELECT name,
  COUNT(DISTINCT(replies.reply_id)) AS replies,
  COUNT(DISTINCT(comments.comment_id)) AS comments
 FROM topics
   INNER JOIN replies
     ON topics.topic_id = replies.topic_id
   INNER JOIN comments
     ON topics.topic_id = comments.topic_id