简体   繁体   中英

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

Suppose I have 2 tables:

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

In order to return the names for id1 and id2 values I tried:

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

which returns:

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

I want the result set to include all RECIPE rows including nulls as shown:

------------------------------------
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

Thanks for all your help...

User Outer joins like-

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

In your query, you are comparing id to fruits'name,which is wrong.

Use LEFT JOIN instead of INNER JOIN to preserve entire output generated by RECIPE table with additional information retrieved from 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

Quote :

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

You need to use outer joins, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM