简体   繁体   English

MySQL:为什么这些查询返回不同的结果?

[英]MySQL: Why do these queries return different results?

Query 1: 查询1:

SELECT * 
FROM user_d1 
WHERE EXISTS (SELECT 1 
              FROM `user_d1` 
              WHERE birthdate BETWEEN '1989-08-04' AND '1991-08-04') 
ORDER BY timestamp_lastonline DESC 
LIMIT 20

Query 2: 查询2:

SELECT * 
FROM user_d1 
WHERE birthdate BETWEEN '1989-08-04' AND '1991-08-04' 
ORDER BY timestamp_lastonline DESC 
LIMIT 20

And what I really don't understand: why does Query 2 return the wrong results? 我真正不明白的是: 查询2为什么返回错误的结果? It returns a list ordered first by birthdate and then by timestamp_lastonline ... 它返回一个列表,该列表首先按birthdate排序,然后按timestamp_lastonline排序...

Query 1 : If at least one record between the dates exists then the entire talbe is retrieved. 查询1 :如果日期之间至少存在一条记录,则检索整个桌布。

Query 2 : Only records between the dates are retrieved. 查询2 :仅检索日期之间的记录。

Read here for how EXISTS works. 在这里阅读EXISTS工作原理。

Your second query uses BETWEEN to return every entry BETWEEN the first entry with '1989-08-04' and the next entry with '1991-08-04' and then orders these by timestamp_lastonline DESC . 您的第二个查询使用BETWEEN返回第一个条目为'1989-08-04'和下一个条目为'1991-08-04'条目,然后按timestamp_lastonline DESC Note that this is literally returning the entries between the two entries with those two values, not every entry that has a year between 1989 and 1991(unless you manually ordered these to be chronologically indexed!). 请注意,这实际上是返回具有这两个值的两个条目之间的条目,而不是每个年份都在1989年至1991年之间的条目(除非您手动将它们按时间顺序编入索引!)。 I'm interested to see what you think your first query returns, as it'll get every entry in the table ordered by timestamp_lastonline if there's a row that the BETWEEN clause returns. 我很想看看您认为您的第一个查询会返回什么,因为如果BETWEEN子句返回一行,它将获得timestamp_lastonline排序的表中的每个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM