简体   繁体   中英

MySQL: Why do these queries return different results?

Query 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:

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? It returns a list ordered first by birthdate and then by timestamp_lastonline ...

Query 1 : If at least one record between the dates exists then the entire talbe is retrieved.

Query 2 : Only records between the dates are retrieved.

Read here for how EXISTS works.

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 . 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!). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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