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

前端 未结 7 1172
故里飘歌
故里飘歌 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条回答
  •  -上瘾入骨i
    2020-12-03 18:30

    If the two queries return different number of columns, you can pad one of the results with empty columns and also add an identifier column first.

    SELECT SQL_CALC_FOUND_ROWS 1 query_type, mytable.*, 
    '' col1, '' col2, '' col3, '' col4
    FROM mytable
    WHERE x = 1
    
    UNION ALL
    
    SELECT 2, mytable2.*
    FROM mytable2
    WHERE 
    FOUND_ROWS() = 0 AND x = 2;
    

    Where mytable2 has 4 more columns than mytable.

提交回复
热议问题