选择具有相同ID的行并选择没有相同ID的剩余行

时间:2011-12-09 14:51:40

标签: sql-server tsql select

我需要首先选择具有公共ID的行,然后选择没有公共ID的剩余行(不重复。)

这是我到目前为止所做的:

SELECT DISTINCT a.cars,b.wheels,c.glass
FROM table auto a, tires b, window c
WHERE a.ID = b.ID AND c.ID = a.ID
????AND/OR a.ID <> b.ID????

&lt; - 最后选择A和B没有共同ID但没有重复记录的行

自动

id cars
1   data
2   data
3   data
4   data

轮胎

id wheels
1   data
2   data
5   data  <-- ID different from table 'Auto' but still want to select it
9   data  <-- ID different from table 'Auto' but still want to select it
200 data  <-- ID different from table 'Auto' but still want to select it

窗口

id glass
1  data
2  data
3  data
4  data

1 个答案:

答案 0 :(得分:3)

使用LEFT JOIN,而不是通过WHERE子句的隐式INNER JOIN,将返回auto表中的匹配和不匹配行。

SELECT DISTINCT a.cars, b.wheels, c.glass
    FROM auto a
        LEFT JOIN tires b
            ON a.id = b.id
        LEFT JOIN window c
            ON a.id = c.id
    ORDER BY a.cars, b.wheels, c.glass