MySql查询:获取查询中的记录计数

时间:2015-11-16 19:19:33

标签: mysql

我的查询工作正常,但在左外连接中没有计算行数。

 SELECT mUserId,mUserName,COALESCE(x.likeId,0) AS likeCount 
    FROM likes 
    LEFT JOIN members ON likes.likeMember = members.mUserId 
    LEFT OUTER JOIN (SELECT likeId, count(*) n FROM likes WHERE likeMember = likes.likeMember) x ON likes.likeMember = x.likeId 
    WHERE likeDate > '2014-11-16 07:44:47' 
    GROUP BY likeMember 
    ORDER BY `likeCount` DESC

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT mUserId,mUserName,COALESCE(x.likeId,0) AS likeCount 
FROM likes LEFT JOIN
     members
     ON likes.likeMember = members.mUserId LEFT OUTER JOIN
     (SELECT likeId, count(*) n
      FROM likes
      WHERE likeMember = likes.likeMember
     ) x
     ON likes.likeMember = x.likeId 
WHERE likeDate > '2014-11-16 07:44:47' 
GROUP BY likeMember 
ORDER BY `likeCount` DESC;

这有点荒谬。在子查询中进行聚合。或者在外部查询中进行聚合。但不是两个。我怀疑你想要更像这样的东西:

SELECT m.mUserId, m.mUserName, COUNT(*) AS likeCount 
FROM likes l LEFT JOIN
     members m
     ON l.likeMember = m.likeId 
WHERE l.likeDate > '2014-11-16 07:44:47' 
GROUP BY l.likeMember 
ORDER BY `likeCount` DESC;

子查询的问题是WHERE子句。您认为它与外部查询相关。但它实际上被解释为:

      WHERE likes.likeMember = likes.likeMember

换句话说,只要likes.likeMember不是NULL,条件就为真。