代码之家  ›  专栏  ›  技术社区  ›  George Menoutis

排除的联合组件的快捷方式非求值

  •  1
  • George Menoutis  · 技术社区  · 7 年前

    假设我有3个具有相同列t1、t2、t3的表,然后运行

    select * 
    from
      (
        select 't1' as source, * from t1
        union all
        select 't2' as source, * from t2
        union all
        select 't3' as source, * from t3
      ) view_code 
    where source='t3'
    

    优化器是否足够聪明,甚至不运行select from t1/t2查询?

    编辑:我运行以下查询:

    select * from (
    select top 1000 '1' as source, map,pda,item from pt
    union all
    select top 1000 '2' as source, map,pda,item from gt
    )t
    where source='2'
    

    果然,gt上只有索引扫描,而pt上根本没有读取操作但我想确认一下每次都是这样。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Max Szczurek    7 年前

    是的。查看执行计划-仅扫描T3。

    create table t2 (col1 nvarchar(max), col2 nvarchar(max))
    create table t3 (col1 nvarchar(max), col2 nvarchar(max))
    
    insert into t1 values ('¿col1?', '¿col2?')
    insert into t2 values ('¿col1?', '¿col2?')
    insert into t3 values ('¿col1?', '¿col2?')
    
    select * from ( 
    select 't1' as source, * from t1 
    union all 
    select 't2' as source, * from t2 
    union all 
    select 't3' as source, * from t3 
    )view_code where source='t3'
    

    enter image description here