简体   繁体   中英

MySQL Select another row if one doesn't exist

I need to select a row from the table with the specific id, but if the row doesn't exist I need to select the first row. is it possible to do it in a single query?

example: I have a table with an id and text fields. and I have 3 rows in the table

id    txt
----------------
1     text1
2     text2
3     text3

I need to select the first row if say SELECT * FROM myTable WHERE id = 4 doesn't exist Else select the row with id 4.

Try this:

SELECT * FROM 
   (SELECT * FROM your_table
      WHERE id = your_id
      LIMIT 1
    UNION
    SELECT * FROM your_table
      LIMIT 1) a
LIMIT 1

The idea is to take first desired row and appending to this very first row, finally taking first one. If desired row does not exists, first one will be selected...

SELECT * FROM (
   SELECT * FROM table1 WHERE [..your criteria...] LIMIT 1
   UNION
   SELECT * FROM table1 LIMIT 1    
) LIMIT 1

Here there is another way that may be considered

SELECT * FROM table1  
WHERE [criteria 1] AND [criteria 2]  

UNION 

SELECT * FROM table1  
WHERE [criteria 1] AND NOT EXISTS 
(
   SELECT * FROM table1  
   WHERE [criteria 1] AND [criteria 2]    
)

LIMIT 1;

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