MYSQL if a select query returns 0 rows then another select query?

前端 未结 7 1175
故里飘歌
故里飘歌 2020-12-03 18:01

if select * from table where x=1 returns 0 rows, then I need select * from table where x=2 [or some other query]. Is it possible to do this in a si

7条回答
  •  不思量自难忘°
    2020-12-03 18:34

    This appears to work from a quick test I just did and avoids the need to check for the existence of x=1 twice.

    SELECT SQL_CALC_FOUND_ROWS *
    FROM mytable
    WHERE x = 1
    
    UNION ALL
    
    SELECT *
    FROM mytable
    WHERE 
    FOUND_ROWS() = 0 AND x = 2;
    

    Edit: Following your clarification to the question obviously the 2 queries will need to be UNION compatible for the above to work.

    The answer to your updated question is No. This is not possible in a single query. You would need to use some conditional procedural logic to execute the desired query.

提交回复
热议问题