SQL查询具有不同的结果

时间:2012-09-21 08:31:32

标签: mysql

SELECT postID, threadID, COUNT(DISTINCT postID) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (468)
AND groupID IN (4,10)
AND isDisabled != 1
AND isDeleted != 1
ORDER BY postID ASC

Chris = groupID 4

Sebastian S. = groupID 10

结果:

 postID  threadID  count 
  2811     468      2

一切都是正确的。

enter image description here

SELECT postID, threadID, COUNT(DISTINCT postID) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (68)
AND groupID IN (7)
AND isDisabled != 1
AND isDeleted != 1
ORDER BY postID ASC

talishh和Bender = groupID 7

结果:

postID  threadID    count
349 (wrong!) 68        3

结果应该是308,因为我想要最老的帖子(这就是我通过postID ASC订购的原因)。 enter image description here 有没有办法优化这个查询?

1 个答案:

答案 0 :(得分:1)

这是因为mysql对聚合函数(COUNT,MIN ...)和分组非常慷慨。 不好的部分:你无法控制它如何分组...... 并且ORDER BY似乎无法解决您的问题。

其他DBMS(和ANSI SQL)强制您在使用其中时不对聚合函数中的字段进行分组。看起来很无聊,但“你知道你得到了什么”。

在你的情况下,只需使用PostID上的MIN和GROUP BY threadID就可以了。

SELECT MIN(postID), threadID, COUNT(*) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (68)
AND groupID IN (7)
AND isDisabled != 1
AND isDeleted != 1
group by threadID

顺便说一下,当你在where语句中使用你的连接实体时,你的LEFT JOIN没有意义(如果我没错)。

如果只放一个值,则无需使用IN,但我想这只是示例代码。

无需使用COUNT(distinct postID)进行正确的分组。只需使用COUNT(*)

即可