简体   繁体   中英

MYSQL SELECT with contradictory LIMITs

There is a table with one date field

The question is: Is there a way to select 10 records AFTER today AND 10 records BEFORE today :)

Of course, instead of making two queries

    SELECT xxxx FROM xxxx WHERE thedate >= 'date' ORDER BY thedate DESC LIMIT 10

and

 SELECT the same WHERE thedate < 'date' ORDER BY thedate ASC LIMIT 10

LIMIT is preferred. Just because of speed.

The data in thedate field is NOT predictable. There can be one or two records with the same date or no records for date.

  SELECT xxxx FROM xxxx WHERE thedate >= 'date' ORDER BY thedate DESC LIMIT 10
union all
SELECT xxxx FROM xxxx WHERE thedate < 'date' ORDER BY thedate ASC LIMIT 10
SELECT xxxx FROM xxxx WHERE thedate > CURDATE() ORDER BY thedate DESC LIMIT 10
union
SELECTxxxx FROM xxxx WHERE thedate < CURDATE() ORDER BY thedate ASC LIMIT 10

You can substract both dates and make the difference absolute:

SELECT xxxx FROM xxxx ORDER BY ABS(UNIX_TIMESTAMP(thedate) - UNIX_TIMESTAMP('date'))

However, it would be much easier to just join the two queries using UNION :

SELECT ... UNION SELECT ...

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