SQL server where子句(比较更多值中的更多值)

时间:2015-09-30 14:09:30

标签: sql sql-server where

SELECT * FROM Customers
WHERE ('Paris','London', 'Dublin', 'Venice')  in (SELECT city FROM Europe)

SELECT city FROM Europe返回多个值,

我该怎么做?

我不想重复这样的条件:

WHERE ('Paris')  in (SELECT city FROM Customers) 
      or ('London')  in (SELECT city FROM Customers) 
      or  ('Dublin')  in (SELECT city FROM Customers) or ....

2 个答案:

答案 0 :(得分:4)

您的第二个选择是多余的,您只需“翻转”in条件。

您的查询等效于:

SELECT * FROM Customers
WHERE city in ('Paris','London', 'Dublin', 'Venice')

<强>更新

根据您在评论中披露的逻辑,您的查询应该是:

select * from Customers
where exists(select top 1 * from Europe where city in ('Paris','London', 'Dublin', 'Venice'))

正如所述:如果在Europe中存在('巴黎','伦敦','都柏林','威尼斯')中的至少一个城市,那么Customers中的所有内容都将被选中,否则什么都不会被选中。

答案 1 :(得分:1)

您可以使用in和列名称。 IN相当于or,在您的情况下为city = 'Paris' or city = 'London' ..

SELECT * FROM Customers
WHERE city in ('Paris','London', 'Dublin', 'Venice') 

修改:使用exists

SELECT c.* FROM Customers c
WHERE exists (select 1 from Europe where city = c.city
              and city in ('Paris','London', 'Dublin', 'Venice')