2017-10-18 175 views
1

我有2個表,通過查詢說明:如何根據記錄存在從2個表中選擇1條記錄?

CT_Validation

select ValidationID, Message from CT_Validation 

ValidationID Message 
====================================================== 
IP_Validator Not a valid IP address 
NumbersOnly  Invalid number. 
SSN    Not a valid social security number. 
10Digits  A 10-digit number is required. 

CT_Validation_Lang

select ValidationID, LangID, Message from CT_Validation_Lang 

ValidationID LangID Message 
====================================================== 
SSN   es  Peligro es mi segundo nombre! 

我如何將建立一個連接,這樣,如果LangID = 'es'我會回來:

ValidationID Message 
====================================================== 
IP_Validator Not a valid IP address 
NumbersOnly  Invalid number. 
SSN    Peligro es mi segundo nombre! 
10Digits  A 10-digit number is required. 

...但如果LangID爲空,空,或者不是「ES」,結果將回復到所有英語以外的其他:

ValidationID Message 
====================================================== 
IP_Validator Not a valid IP address 
NumbersOnly  Invalid number. 
SSN    Not a valid social security number. 
10Digits  A 10-digit number is required. 

重要提示:鍵字段是ValidationID和重要的關鍵值在這個例子中是SSN,因爲它存在於兩個表中。

在此先感謝您的任何建議。

+0

的[我可以使用CASE語句JOIN條件?(可能的複製https://stackoverflow.com/questions/10256848/can-i-use-case-statement-in-a-join-條件) –

回答

2

我想你想left join和​​3210

select cv.ValidationID, coalesce(cvl.Message, cv.Message) 
from CT_Validation cv 
left join CT_Validation_Lang cvl on cv.ValidationID = cvl.ValidationID 
    and cvl.LangID = 'es' 

這將從CT_Validation_Lang選擇Message,如果它存在LangIDes。連同left join

select 
    ctv.ValidationID, 
    coalesce(
      (select 
      ctvl.Message 
      from 
      CT_Validation_Lang ctvl 
      where 
      ctvl.ValidationID = ctv.ValidationID and 
      LangID = 'es' 
      ), 
      ctv.Message, ' ') as Message 
    from 
    CT_Validation ctv; 
+0

工程太棒了!謝謝FuzzyTree。 – HerrimanCoder

0

你可以這樣做:

select v.ValidationID, coalesce(vl.message, v.message) as message 
from CT_Validation v left join 
    CT_Validation_Lang vl 
    ON vl.ValidationID = v.ValidationID and vl.LangID = 'es'; 

這將從CT_Validation_Lang選擇消息時,西班牙語翻譯可用。否則,它會選擇原始消息。

0

喜歡的東西回落到Message

select a.ValidationID, ISNULL(b.message, a.message) 
from CT_Validation a 
left join CT_Validation_Lang b on a.ValidationID = b.ValidationID and b.LangID = 'es' 
1

一種方式與CASE

SELECT 
    ctv.ValidationID, 
    CASE WHEN ctvl.LangID = 'es' THEN ctvl.message ELSE ctv.message END AS Message 
FROM CT_Validation ctv 
LEFT JOIN CT_Validation_Lang ctvl ON ctv.ValidationId = ctvl.ValidationId 
    AND ctvl.LangID = 'es' 
0

使用ISNULL()功能 - :否則,它會從CT_Validation

相關問題