Tsql从AND条件中选择相关表

时间:2011-11-16 16:37:56

标签: sql tsql

我有两个相关的表格:

表1

Id
-----
1
2
3

表2

Id     Feature
--------------
1      Car
1      Moto
1      Camper
2      Moto
2      Scooter
3      Apple

我想选择具有“Car”和“Moto”的ID。 因此,在示例中,我只想获得Id = 1。

3 个答案:

答案 0 :(得分:2)

使用INTERSECT运算符:

select id from table2 where feature = 'Car'
intersect 
select id from table2 where feature = 'Moto'

答案 1 :(得分:1)

此:

WITH    features AS
        (
        SELECT  feature
        FROM    (
                VALUES
                ('Car'),
                ('Moto')
                ) q (feature)
        )
SELECT  *
FROM    table1 t1
WHERE   NOT EXISTS
        (
        SELECT  feature
        FROM    features
        EXCEPT
        SELECT  feature
        FROM    table2 t2
        WHERE   t2.id = t1.id
        )

或者这个:

SELECT  *
FROM    table t1
WHERE   (
        SELECT  COUNT(*)
        FROM    table2 t2
        WHERE   t2.id = t1.id
                AND t2.feature IN ('Car', 'Moto')
        ) = 2

哪种查询更有效取决于您在两个表中有多少记录以及有多少匹配。

答案 2 :(得分:0)

此选择将两个LEFT OUTER JOIN添加到table2(一个基于'Car',另一个基于'Moto'),并确保每个JOIN都返回了一个结果。 DISTINCT确保您只获得一次ID。

SELECT DISTINCT t1.id
FROM table2 t2
LEFT OUTER JOIN table2 t2_2 ON t2.id = t2_2.id AND t2_2.feature = 'Moto'
WHERE t2.feature = 'Car'
AND t2_2.id IS NOT NULL

编辑:删除了与table1的连接,因为它确实不需要。