SQL IF SELECT query is null then do another query

前端 未结 3 1549
时光说笑
时光说笑 2021-01-19 07:18

I have a query that regularly returns \"nothing\", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be

3条回答
  •  醉梦人生
    2021-01-19 07:36

    There are some simple way only use sql.

    Define your first query as a temp table, with union all, filter the second query with temp table's count.

    with temp as (select * from t1 where 1=0)
    select * from temp
    union all
    select * from t2 where (select count(*) from  temp) =0
    

    This query will return the second table's records.

    with temp as (select * from t1 )
    select * from temp
    union all
    select * from t2 where (select count(*) from  temp) =0
    

    And if temp query have result, only return temp query.

    You can test with sql fiddle here.

提交回复
热议问题