【问题标题】:select count of rows from 2 tables and merge into one row (mysqli)从 2 个表中选择行数并合并为一行(mysqli)
【发布时间】:2014-10-26 12:48:24
【问题描述】:

我通过 php 和 mysqli 创建了一个像 facebook 这样的网络应用程序

在我的应用程序中,我有一个帖子表,一个点赞表和一个 cmets 表

我想用他的 post_id 获取一行中每个帖子的 cmets 和喜欢的数量!!!

我尝试了一些这样的查询:

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`

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

【问题讨论】:

  • 我们也不知道您的问题。介意告诉我们你期望的结果,以及你确实得到了什么:)?

标签: php mysql select join union


【解决方案1】:

您可以使用两个左连接来计算不同值。

如果tbllikestblcomments 表中有字段like_idcomment_id,这样的方法会起作用

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

【讨论】:

    【解决方案2】:

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

    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;
    

    这只会让您发布既有喜欢又有 cmets 的帖子。要获得您想要的,请使用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;
    

    【讨论】:

    • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在 '(c.comment_num, 0) as c_num, COALESCE(l.like_num, 0) as l_num from tblpo' 附近使用第 2 行
    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 2013-06-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2013-11-28
    • 2019-08-02
    • 2019-01-14
    相关资源
    最近更新 更多