【问题标题】:Two SQL statements, ignore the return of the first if it has no results?两条sql语句,如果没有结果就忽略第一个的返回?
【发布时间】:2013-04-02 18:24:10
【问题描述】:

我有一个sql语句SELECT * FROM table1 WHERE ....; SELECT * FROM table2 WHERE ....

我想要的是从第一个 select 语句中获取结果,如果它返回结果,但如果没有,我想忽略它,只从第二个 select 语句中获取结果。有没有办法只使用 SQL 来做到这一点?

我将它作为数据表返回给我,使用数据适配器填充上述 SQL 语句中的数据表。我无法更改该部分,或切换到填充数据集(出于我不会进入的原因,但无法更改)。

【问题讨论】:

    标签: sql sql-server vb.net tsql


    【解决方案1】:

    假设两个查询返回相同数量和类型的列,一种方法是:

    select * from table1 where ... /* query 1 conditions */
    union all
    select * from table2 where ... /* query 2 conditions */
    and not exists
    (select 1 from table1 where ... /* query 1 conditions */)
    

    【讨论】:

    • 我喜欢这个,但是这两个语句不会总是返回相似的结果,这使我受到第一个 select 语句返回的列的限制。
    【解决方案2】:

    几个选项。您可以先查看计数:

    If (select count(*) from table1 where...) > 0
    begin
        select * from table1 where...
    end
    else
    begin
        select * from table2 where...
    end;
    

    如果两个结果集的结构相同,则可以使用临时表保存计数检查(从而提高性能):

    create table #temp (col1 int, col2 varchar(10), ...);
    
    insert #temp
    select * from table1 where...;
    
    if @@rowcount = 0 
    begin
        insert #temp
        select * from table2 where...
    end;
    
    select * from #temp;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 2014-08-17
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2011-02-16
      相关资源
      最近更新 更多