简体   繁体   中英

SQL LIMIT keyword: Ensure a specific result is included

I need to write an SQL prefetcher along the lines of

SELECT * WHERE id == x OR id >= y LIMIT 100 FROM ...

where I need the result id == x to be included, while the other results are just bonus. Is this possible? If not, I am thinking if the ids are sorted, and the returned results are in their ordering, I can still make the query in a way where it is guaranteed to include id == x. But could be tricky.

Edit: So the answer(from rbm) is this:

(SELECT * WHERE id == x)
UNION
(SELECT * WHERE id > y LIMIT 100) 

Note: It's ok that I may have +-1 number of results

If you need id = x to be included, do something like this:

select case when id = x then 1 else 2 end sortOrder
etc
order by sortOrder

After putting it to SQL syntax, it would look like :

SELECT *
FROM ...
WHERE id = x OR id >= y
ORDER BY CASE WHEN id = x THEN 0 ELSE 1 END ASC
LIMIT 100

EDIT : Reminder: Limit is applied after order.

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