MySQL SELECT DISTINCT 的行为不符合预期
好吧,这真的让我很困惑。
此查询返回预期结果,尽管有重复的 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:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为这与您的问题严格相关,但是:
不是有效的标准 SQL 语法。可能有许多行具有相同的
car_id
和不同的created
值。订购时应该使用哪一种?也许您想重写查询以便它返回有意义的结果:
I don't think that this is strictly relevant with your problem but:
is not valid standard SQL syntax. There may be many rows with same
car_id
and differentcreated
values. Which one should be used for the ordering?Perhaps you want to rewrite the query so it returns meaningful results:
您按
updates.created
进行订购。据推测,这意味着每个不同的carid
都会出现,只是不完全在您期望的位置。尝试按carid
排序来执行比较。You're ordering by
updates.created
. Presumably this means that each distinctcarid
will come up, just not exactly where you expect it to. Try ordering bycarid
to perform the comparison.像这样的东西会起作用吗:
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