php查询有2个计数和连接

时间:2012-02-20 14:18:47

标签: php mysql

我运行一个查询,使用3个标签“发布,喜欢和评论”我需要获得帖子所拥有的喜欢和评论的大量,同时从帖子表中获取基本信息所以我使用查询下面但问题是它将值likeAmount复制到commentAmount如果喜欢更大,除非注释为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"

所以这不起作用,但当我添加不同它确实有效,所以当它像这样:。

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";

我不明白为什么它适用于不同而且没有用,并且明确地表现出独特的性能,或者它是否会产生差异性,它将用于具有交通流量的网站中。

2 个答案:

答案 0 :(得分:2)

试试这个,不是简短的,而是可读的:

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 :(得分:0)

也许使用SUM而不是COUNT来处理没有连接的记录会起作用,并且应该同样快地执行:

SELECT post.id, 
       SUM(IF(likes.id IS NULL,0,1)) as 'LikeAmount', 
       SUM(IF(comment.id IS NULL,0,1)) 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"