Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select another row if one doesn't exist

Tags:

mysql

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.

like image 559
Headshota Avatar asked Feb 03 '23 12:02

Headshota


1 Answers

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

like image 59
Marco Avatar answered Feb 05 '23 00:02

Marco