几个ID发送到" in"?

时间:2018-02-20 08:48:04

标签: sql

我想要这样的事情。

select car.name
from car
where 
(1 AND 2) IN (Select c.ConfigItemId from Contract c where c.ContractId = 
Car.ContractId)

看起来很简单,但我还没有找到解决方案。 我唯一发现的是每个id匹配一行。

" AND (1) IN (Select c.ConfigItemId from Contract c where c.ContractId = 
Car.ContractId)"
 AND (2) IN (Select c.ConfigItemId from Contract c where c.ContractId = 
Car.ContractId)"

这样做的最佳方式是什么?

我想我需要澄清一下。 我希望它对我发送的所有值都是必要的" i,2"存在于contract.configid。

3 个答案:

答案 0 :(得分:3)

您可以INNER JOININ

来实现
select car.name from car
INNER JOIN Contract as c on c.ContractId = Car.ContractId
where c.ConfigItemId IN (1,2)
GROUP BY c.ContractId
HAVING COUNT(distinct c.ConfigItemId) > 1

答案 1 :(得分:1)

从性能角度来看,EXISTS会更好,但是这样的东西可能会有效。

select car.name from car
join Contract c on c.ContractId = car.ContractId
where c.ConfigItemId in (1,2)

答案 2 :(得分:1)

您可以使用简单的存在:

select  car.name
from    car
where   EXISTS (
                    SELECT  NULL
                    FROM    Contract c 
                    WHERE   c.ContractId = Car.ContractId
                        AND c.ConfigItemId IN (1, 2)
                    GROUP BY c.ContractId
                    HAVING   COUNT(distinct c.ConfigItemId) > 1
                )