如何查询列出子查询表SQL中的列的某些元素。存在,IN?

时间:2016-01-14 12:58:07

标签: sql sql-server

我只会告诉你们一个例子:我得到了这些表:

表:汽车标记

Name | Manufacturer
------------------- 
POLO   VOLKSWAGEN  
A6     AUDI
911    PORSCHE

然后我从子查询中得到这个子表,来自大约三个表:

Manufacturer |  Num of rented cars, by clients age > 50
-------------------------------------------------------
VOLKSWAGEN                      2 
AUDI                            3

我的问题是:如何从此子查询中存在的Car Mark中选择制造商?

我只想要一个输出:

Manufacturer
---------------
VOLKSWAGEN
AUDI 

2 个答案:

答案 0 :(得分:1)

你可以采用不同的方式,我宁愿第一个,因为explain plain看起来更简单,代码也很容易阅读。

<强> SQL FIDDLE DEMO

使用或不使用索引检查每个查询的解释计划。

最后两个有完全相同的计划。我的猜测优化器会将这些转换为相同的查询。

SELECT C.[Manufacturer]
FROM  cars C
LEFT JOIN rented R
       ON C.[Manufacturer] = R.[Manufacturer]
WHERE R.[Manufacturer] IS NOT NULL;

SELECT C.[Manufacturer]
FROM  cars C
WHERE C.[Manufacturer] IN ( SELECT [Manufacturer]
                            FROM rented R );

SELECT C.[Manufacturer]
FROM  cars C
WHERE EXISTS ( SELECT [Manufacturer]
               FROM rented R 
               WHERE R.[Manufacturer] = C.[Manufacturer]);

答案 1 :(得分:0)

尝试

select Manufacturer
from Car_Mark
where Manufacturer in (
    select Manufacturer 
    from (
        --your subquery...
    ) x
)