簡體   English   中英

SQL Server 2008保留表中的行以及其他表中的不匹配值

[英]SQL Server 2008 Preserve rows from table with non-matching values from another table

假設我有2張桌子:

FRUITS           RECIPE
-----------      -----------------
id  name         ver   id1     id2
-----------      -----------------
1   apple        1     1       1
2   banana       2     null    3
3   orange       3     3       3
4   peach        4     4       2
                 5     1       null
                 6     null    null

為了返回id1和id2值的名稱,我嘗試了以下操作:

SELECT ver, id1, F1.name, id2, F2.name
FROM RECIPE INNER JOIN FRUITS AS F1 ON id1 = F1.name
            INNER JOIN FRUITS AS F2 ON id2 = F2.name

返回:

------------------------------------
ver   id1     name       id2    name
------------------------------------
1     1       apple      1      apple 
3     3       orange     3      orange
4     4       peach      2      banana

我希望結果集包括所有包含空值的RECIPE行,如下所示:

------------------------------------
ver   id1     name      id2     name
------------------------------------
1     1       apple     1       apple 
2     null    null      3       orange
3     3       orange    3       orange
4     4       peach     2       banana
5     1       apple     null    null
6     null    null      null    null

感謝你的幫助...

用戶外部加入方式如下:

SELECT ver, id1, F1.name, id2, F2.name
FROM RECIPE 
LEFT JOIN FRUITS F1 
ON id1 = F1.id
LEFT JOIN FRUITS F2 
ON id2 = F2.id

在查詢中,您將ID與水果名稱進行比較,這是錯誤的。

使用LEFT JOIN而不是INNER JOIN來保留RECIPE表生成的全部輸出,以及從FRUITS檢索的其他信息:

SELECT ver, id1, F1.name, id2, F2.name
FROM RECIPE 
LEFT JOIN FRUITS AS F1 ON id1 = F1.name
LEFT JOIN FRUITS AS F2 ON id2 = F2.name

引用

LEFT JOIN關鍵字返回左側表(table1)中的所有行,以及右側表(table2)中的匹配行。 如果沒有匹配項,則結果在右側為NULL。

您需要使用外部聯接,例如

SELECT ver, id1, F1.name, id2, F2.name
FROM RECIPE LEFT OUTER JOIN FRUITS AS F1 ON id1 = F1.name
            LEFT OUTER FRUITS AS F2 ON id2 = F2.name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM