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

前端 未结 7 1178
故里飘歌
故里飘歌 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:15

    SQL_CALC_FOUND_ROWS and FOUND_ROWS cannot be used in a single query, even if separate by UNION statements.

    The correct way to do this would be:

    WITH  my_cte AS
    (
      SELECT * from original_set
    )
    SELECT * FROM my_cte
    UNION ALL
    SELECT opt.* FROM optional_set opt JOIN (SELECT count(*) v FROM my_cte) count ON count.v=0;
    

    With the JOIN and the UNION ALL the performance of this query is almost equivalent to either of the individual standalone queries

提交回复
热议问题