gpt4 book ai didi

mysql - SQL查询有不同的结果

转载 作者:行者123 更新时间:2023-11-29 14:16:45 24 4
gpt4 key购买 nike

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

克里斯 = 组ID 4

塞巴斯蒂安·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有没有办法优化这个查询?

最佳答案

这是因为 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(*)

关于mysql - SQL查询有不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com