当使用COUNT与LEFT OUTER JOIN和GROUP BY时,MySQL包含零行

时间:2013-02-19 16:27:04

标签: mysql count group-by left-join

如何避免以零会议消除用户?我知道有类似的问题,但这段代码要复杂得多。

SELECT user.userID, user.contactName, user.email, COUNT( * ) AS meetingsCount
FROM user
LEFT OUTER JOIN meeting ON user.userID = meeting.userID
WHERE user.userID NOT 
IN ( 1, 2, 3, 4, 5, 59, 62, 63, 64, 66, 69, 71, 72, 73, 78, 107 ) 
AND SUBSTRING( meeting.meetingCode, 5, 2 ) 
BETWEEN 12 
AND 22 
AND SUBSTRING( meeting.meetingCode, 7, 2 ) 
BETWEEN 01 
AND 12 
AND SUBSTRING( meeting.meetingCode, 9, 2 ) 
BETWEEN 01 
AND 31 
GROUP BY user.userID, contactName, email
ORDER BY meetingsCount DESC

1 个答案:

答案 0 :(得分:5)

您需要将会议代码表的逻辑放在您的联接中。否则,匹配您从会议表中过滤掉的记录的用户将被过滤掉您的结果。使您的JOIN基本上成为INNER联接。我想你也应该在BETWEEN子句中的值周围加上单引号。

SELECT  user.userID, user.contactName, user.email, COUNT( meeting.userID ) AS meetingsCount

FROM    user

        LEFT OUTER JOIN meeting ON user.userID = meeting.userID
        AND SUBSTRING( meeting.meetingCode, 5, 2 ) BETWEEN '12' AND '22'
        AND SUBSTRING( meeting.meetingCode, 7, 2 ) BETWEEN '01' AND '12'
        AND SUBSTRING( meeting.meetingCode, 9, 2 ) BETWEEN '01' AND '31' 

WHERE user.userID NOT IN ( 1, 2, 3, 4, 5, 59, 62, 63, 64, 66, 69, 71, 72, 73, 78, 107 ) 

GROUP BY user.userID, contactName, email

ORDER BY meetingsCount DESC