MySQL选择另一行(如果不存在)

问题描述:

我需要从表中选择具有特定ID的行,但是如果该行不存在,则需要选择第一行.可以在单个查询中做到吗?

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?

示例: 我有一个带有ID和文本字段的表格.我在表中有3行

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

如果说SELECT * FROM myTable WHERE id = 4不存在,我需要选择第一行,否则请选择ID为4的行.

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.

尝试一下:

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