MySQL Select another row if it does not exist

I need to select a row from a table with a specific identifier, but if the row does not exist, I need to select the first row. is it possible to do this in one request?

Example: I have a table with identification 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 does not exist. Else selects a row with id 4.

+7
source share
2 answers

Try the following:

 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 the first desired line and add to this very first line, finally, take the first. If the desired row does not exist, the first will be selected ...

+9
source
 SELECT * FROM ( SELECT * FROM table1 WHERE [..your criteria...] LIMIT 1 UNION SELECT * FROM table1 LIMIT 1 ) LIMIT 1 
+3
source

All Articles