MySQL SELECT DISTINCT 的行为不符合预期

发布于 2025-01-02 21:31:14 字数 445 浏览 1 评论 0原文

好吧,这真的让我很困惑。

此查询返回预期结果,尽管有重复的 car_id 数字

SELECT car_id FROM `Updates` ORDER BY `updates`.`created` DESC

。这两个查询返回相同的结果集:

SELECT distinct `Updates`.`car_id` FROM `Updates` ORDER BY `updates`.`created` DESC

SELECT car_id FROM `Updates` GROUP BY car_id ORDER BY `updates`.`created` DESC

请参阅下文了解它们有何不同: 请参阅下文了解它们有何不同:

Ok this has really got me confused.

This query returns the expected results albeit with duplicate car_id numbers

SELECT car_id FROM `Updates` ORDER BY `updates`.`created` DESC

These 2 queries return the same set of results:

SELECT distinct `Updates`.`car_id` FROM `Updates` ORDER BY `updates`.`created` DESC

SELECT car_id FROM `Updates` GROUP BY car_id ORDER BY `updates`.`created` DESC

See below though as to how they differ:
See below though as to how they differ:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦明 2025-01-09 21:31:14

我不认为这与您的问题严格相关,但是:

SELECT DISTINCT car_id 
FROM Updates 
ORDER BY created DESC

不是有效的标准 SQL 语法。可能有许多行具有相同的 car_id 和不同的 created 值。订购时应该使用哪一种?

也许您想重写查询以便它返回有意义的结果:

SELECT car_id 
FROM Updates
GROUP BY car_id 
ORDER BY MAX(created) DESC              --- or MIN(created)
                                        -- whatever suits you

I don't think that this is strictly relevant with your problem but:

SELECT DISTINCT car_id 
FROM Updates 
ORDER BY created DESC

is not valid standard SQL syntax. There may be many rows with same car_id and different created values. Which one should be used for the ordering?

Perhaps you want to rewrite the query so it returns meaningful results:

SELECT car_id 
FROM Updates
GROUP BY car_id 
ORDER BY MAX(created) DESC              --- or MIN(created)
                                        -- whatever suits you
無處可尋 2025-01-09 21:31:14

您按 updates.created 进行订购。据推测,这意味着每个不同的 carid 都会出现,只是不完全在您期望的位置。尝试按 carid 排序来执行比较。

You're ordering by updates.created. Presumably this means that each distinct carid will come up, just not exactly where you expect it to. Try ordering by carid to perform the comparison.

孤芳又自赏 2025-01-09 21:31:14

像这样的东西会起作用吗:

SELECT * FROM Updates GROUP BY car_id ORDER BY 创建的 DESC

Would Something Like This Work:

SELECT * FROM Updates GROUP BY car_id ORDER BY created DESC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文