1

我正在尝试使用 IN 子句,但是过滤需要在由 2 列定义的一组项目上。这可能吗?可能还有其他方法可以做到这一点(例如表变量),但如果可能的话,我想把它作为一个 IN 子句来做,因为这样在我的应用程序中动态创建会更加优雅和简单。

这个伪代码可能会让我更清楚我想要做什么。

SELECT *
FROM Distributors
WHERE (City,State) IN (('Springfield','OH'), ('Springfield','MO'), ('Houston','TX'))
4

5 回答 5

5

最简单的可能是生成一个伪表并对其执行连接。( SQL VALUESServer 2008 或更高版本):

SELECT d.*
FROM Distributors d
JOIN (VALUES ('Springfield','OH'), ('Springfield','MO'), ('Houston','TX'))
    as t(City,State)
ON d.City = t.City and d.State = t.State

或者UNION ALL

SELECT d.*
FROM Distributors d
JOIN (SELECT 'Springfield','OH' UNION ALL SELECT 'Springfield','MO' UNION ALL SELECT 'Houston','TX')
    as t(City,State)
ON d.City = t.City and d.State = t.State

我承认,我不再使用IN了,但是不同元素之间的分隔符都是相同的(在任何一种情况下),所以希望它仍然会命中:

在我的应用程序中动态创建更简单。

(此外,您的尝试不仅合理,而且实际上接近 ANSI 标准中的内容 - 可能值得您在此连接问题上投票)

于 2013-03-19T14:58:30.927 回答
3
select * 
from distributors
where  ( city = 'Springfield' and State = 'OH') OR
       ( city = 'Springfield' and State = 'MO') OR
       ( city = 'Houston' and State = 'TX')

没那么复杂

于 2013-03-19T14:55:53.317 回答
2

可以执行多个IN语句,这可以通过以下方式实现:

 SELECT *
 FROM Distributors
 WHERE CITY IN ('SPRINGFIELD', 'HOUSTON')
 AND STATE IN ('OH', 'MO', 'TX')

但是,您似乎想使用OR

 SELECT *
 FROM Distributors
 WHERE (City = 'Houston' AND State = 'TX') OR
 (City = 'Springfield' AND State = 'OH') OR
 (City = 'Springfield' AND State = 'MO')
于 2013-03-19T14:54:19.700 回答
1

这是一个答案,不是很漂亮,但它有效:

SELECT *
FROM Distributors d
  INNER JOIN (SELECT 
                'Springfield' AS city
                ,'OH' AS state
              UNION 
              SELECT
                'Springfield'
                ,'MO'
              UNION
              SELECT 
                'Houston'
                ,'TX') x
WHERE d.city = x.city
  AND d.state = x.State
于 2013-03-19T15:02:29.523 回答
0

不支持此构造。但是,您可以以与其他建议略有不同的方式编写此代码:

SELECT <column list>
FROM dbo.Distributors
WHERE (City = 'Springfield' AND State IN ('OH', 'MO'))
   OR (City = 'Houston' AND State = 'TX');
于 2013-03-19T15:05:23.463 回答