从2个表中选择行数并合并为一行(mysqli)

时间:2014-10-26 12:48:24

标签: php mysql select join union

我通过php和mysqli

创建了一个像facebook这样的网络应用程序

在我的应用程序中,我有一个帖子表,一个用于喜欢的表和一个用于评论的表

我想用他的post_id !!!获取每行中评论和喜欢的数量

我尝试了一些像这样的问题:

select `tblpost`.`post_id`,  COALESCE(TCOMM.`comment_num`,0) as `c_num`, COALESCE(TLIKE.`like_num`,0) as `l_num`
from 
(select `tblpost`.`post_id`, count(*) as `like_num` from `tblpost` join `tbllikes` on `tbllikes`.`post_id` = `tblpost`.`post_id` group by `tblpost`.`post_id`
) TLIKE
inner join
(select `tblpost`.`post_id`, count(*) as `comment_num` from `tblpost` join `tblcomments` on `tblcomments`.`post_id` =  `tblpost`.`post_id` group by `tblpost`.`post_id`) TCOMM
on
    TCOMM.`post_id` = TLIKE.`post_id`

但我不知道我的问题是什么

2 个答案:

答案 0 :(得分:2)

您可以使用两个左连接进行计数。

如果表like_idcomment_id

中有字段tbllikestblcomments,则此类内容有效
SELECT 
    tblpost.post_id AS post_id, 
    COUNT(DISTINCT tbllikes.like_id) AS likes,
    COUNT(DiSTINCT tblcomments.comment_id) AS comments
FROM tblpost 
LEFT JOIN tbllikes ON tbllikes.post_id = tblpost.post_id
LEFT JOIN tblcomments on tblcomments.post_id =  tblpost.post_id
GROUP BY tblpost.post_id

答案 1 :(得分:1)

首先,我认为您可以大大简化您的查询:

select l.post_id,
        COALESCE(c.comment_num, 0) as c_num, COALESCE(l.like_num, 0) as l_num
from  (select l.post_id, count(*) as like_num
       from tbllikes l 
       group by l.post_id
      ) l inner join
      (select c.post_id, count(*) as comment_num
       from tblcomments c
       group by c.post_id
      ) c
      on l.post_id = c.post_id;

这只会让你有喜欢和评论的帖子。要获得所需内容,请使用left join

select p.post_id,
      COALESCE(c.comment_num, 0) as c_num, COALESCE(l.like_num, 0) as l_num
from tblpost p left join
     (select l.post_id, count(*) as like_num
      from tbllikes l 
      group by l.post_id
     ) l
     on l.post_id = p.post_id left join
     (select c.post_id, count(*) as comment_num
      from tblcomments c
      group by c.post_id
     ) c
     on c.post_id = p.post_id;