简体   繁体   中英

MySQL selection order where multiple columns are conditions

I want to do:

SELECT * FROM table WHERE id1 = '123' OR id2= '456' OR id3 = '789' LIMIT 1;

There may be multiple matches, and if that is the case, I want the match from id1 to be returned first, the match from id2 to be returned second, and the match from id3 to be returned third.

I know I can accomplish this via 3 queries, something like:

SELECT * FROM table WHERE id1 = '123' LIMIT 1

if no matches, then:

SELECT * FROM table WHERE id2 = '456' LIMIT 1

if no matches, then:

SELECT * FROM table WHERE id3 = '789' LIMIT 1

There must be a better way. what is the best and most efficient query to accomplish this?

In MySQL you can order by boolean expressions. I think they are translated to 0 and 1, so with a descending sort, you can get the 'true-ish' values first. That way you can sort by the three expressions one after each other:

SELECT * FROM table 
WHERE id1 = '123' OR id2= '456' OR id3 = '789' 
ORDER BY 
  id1 = '123' DESC,
  id2 = '456' DESC, 
  id3 = '789' DESC 
LIMIT 1;

This will even go further than the separate queries, because if there is a row that matches all three ids, that row will be returned first.

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