如果找到其他记录,则从另一个表中选择值,使用当前表上的值

时间:2016-03-29 13:56:21

标签: sql sql-server

如果匹配存在,我试图从另一个table2获取值,否则,选择table1中的值,但执行查询需要很长时间。

select table1.field1, table1.field2, 
case 
    when exist (select top 1 
                from table2 
                where table2.field1=table1.field3
                and table2.field2 is not null 
                order by date desc) 
    then (select top 1
            from table2 
            where table2.field1=table1.field3 
            and table2.field2 is not null 
            order by date desc) 
    else table1.field3 
end 
from table1

重写此查询的其他任何方式?

请帮忙! n00b :(

3 个答案:

答案 0 :(得分:2)

是。使用outer apply

select t1.field1, t1.field2, coalesce(t2.??, t1.field3)
from table1 t1 outer apply
     (select top 1 t2.*
      from table2 t2
      where t2.field1=  t1.field3 and t2.field2 is not null
      order by t2.date desc
     ) t2;

目前还不清楚你在说什么领域,因为问题中缺少这个领域;因此,??

答案 1 :(得分:0)

SELECT t1.field1, t1.field2, coalesce(t2.field2,t1.field3) as field3
FROM table1 t1
LEFT JOIN table2 t2
on t2.field1=t1.field3  
and t2.date = (select max(date) from table2 t2e where t2.field1=t2e.field2)

答案 2 :(得分:0)

SELECT
    table1.field1, 
    table1.field2, 
    COALESCE(table2.field2,table1.field3)
FROM
    table1
LEFT OUTER JOIN 
    table2
ON
    table2.field1=table1.field3
  • COALESCE会跳过列表中的所有空值。
  • LEFT OUTER JOIN返回第一个表中的所有值,但将空值放在第二个表中没有对应行的位置。