doucuo9126 2012-02-20 14:18
浏览 23
已采纳

php查询有2个计数和连接

im running a query that usses 3 tabels "post, likes and comment" i need to get the ammount of likes and comments the post has got, and at the same time get the basic info from the post table so im using the query bellow but the problem is that it copys the value likeAmount to commentAmount if likes is bigger unless comments is 0.

SELECT post.*, COUNT(likes.id) as 'LikeAmount', COUNT(comment.id) as 'commentAmount' FROM post 
  LEFT JOIN likes ON post.id = likes.post
  LEFT JOIN comment ON post.id = comment.post
  GROUP BY post.id 
  ORDER BY LikeAmount DESC"

so that doesnt work but when i add distinct it does work, so when its like this:.

SELECT post.*, COUNT(distinct likes.id) as 'LikeAmount', COUNT(distinct comment.id) as 'commentAmount' FROM post 
LEFT JOIN likes ON post.id = likes.post
LEFT JOIN comment ON post.id = comment.post
GROUP BY post.id 
ORDER BY LikeAmount DESC";

i dont see why it works with distinct and doesnt with out, and does distinct mather performance wise or does it make no diffrence sinds it will be used in a website that has a lott of trafic..

  • 写回答

2条回答 默认 最新

  • douyanpeng0748 2012-02-20 14:27
    关注

    try this, not short, but readable:

    SELECT
        p.*,
        pl.like_count,
        pc.comment_count
    FROM post p
    
    #join likes
    LEFT OUTER JOIN (
        SELECT
            post,
            COUNT(*) AS like_count
        FROM likes
        GROUP BY post
    ) AS pl
        ON pl.post = p.id
    
    #join comments
    LEFT OUTER JOIN (
        SELECT
            post,
            COUNT(*) AS comment_count
        FROM comment
        GROUP BY post
    ) AS pc
        ON pc.post = p.id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图