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...