WHERE ... IN有多列

时间:2014-08-05 14:40:03

标签: sql sql-server

我尝试让一些符合特定条件的用户:

SELECT * FROM users
WHERE lastname IN ('Pitt','Jolie','Costner') 
AND firstname IN ('Brad','Angelina','Kevin')

但是这样,Kevin Jolie和Brad Costner将会出现,这不是我需要的。

所以我试过了:

SELECT * FROM users
WHERE (lastname,firstname) IN ('Pitt','Brad'),('Jolie','Angelina'),('Costner','Kevin')

引发错误:

An expression of non-boolean type specified in a context where a condition is expected, near ','.

您是否知道会产生预期结果的查询?

Attn:两列或更多列并不总是varchar列,它们可以是任何类型。

2 个答案:

答案 0 :(得分:2)

请试试。

SELECT * FROM users
WHERE lastname+firstname IN ('PittBrad','JolieAngelina','CostnerKevin')

如果列为null,则

SELECT * FROM users
WHERE ISNULL(lastname,'')+ISNULL(firstname,'') IN ('PittBrad','JolieAngelina','CostnerKevin')

答案 1 :(得分:1)

我会使用这样的查询(但我使用的是SQL-Server 2005,也许现在有些东西了):

SELECT * FROM users
WHERE 
    (firstname = 'Angelina' AND lastname = 'Jolie') 
OR
    (firstname = 'Brad' AND lastname = 'Pitt') 
OR
    (firstname = 'Kevin' AND lastname = 'Costner')