2016-03-29 15 views
-1

Başka bir tablo2 değerlerini almaya çalışıyorum, başka bir tablo varsa, tablo1'deki değeri seçin, ancak uzun bir zaman alıyor sorguyu yürüt.kayıt başka bir tablodan başka bir tablo seçin, geçerli tablodaki değeri kullanın

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 

Bu sorguyu yeniden yazmanın başka bir yolu var mı?

lütfen yardım edin! . N00b burada :(

+0

'table2' –

cevap

2

Evet outer apply kullanın:

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; 

söz eksik çünkü sen neden bahsediyorsun hangi alanda belli değildir; dolayısıyla ??

+0

'dan hangi alanı almak istediğinizi çok teşekkürler! :-) – Queen

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) 
0
SELECT 
    table1.field1, 
    table1.field2, 
    COALESCE(table2.field2,table1.field3) 
FROM 
    table1 
LEFT OUTER JOIN 
    table2 
ON 
    table2.field1=table1.field3 
.
  • COALESCE listedeki tüm boş değerleri atlar
  • SOL OUTER JOIN, ilk tablodaki tüm değerleri döndürür, ancak ikinci tabloda karşılık gelen satır bulunmayan boş değerleri koyar.
İlgili konular