SQL Server - 包含多个字段的IN子句

ope*_*sas 18 sql-server select in-clause sql-server-2008

是否可以在IN子句中包含多个字段?类似于以下内容:

select * from user
where code, userType in ( select code, userType from userType )
Run Code Online (Sandbox Code Playgroud)

我正在使用ms sql server 2008


我知道这可以通过连接和存在来实现,我只是想知道它是否可以用该IN子句完成.

Ode*_*ded 15

不是你发布的方式.您只能返回单个字段或类型IN才能工作.

来自MSDN(IN):

test_expression [ NOT ] IN 
    ( subquery | expression [ ,...n ]
    ) 

subquery - Is a subquery that has a result set of one column. 
           This column must have the same data type as test_expression.

expression[ ,... n ] - Is a list of expressions to test for a match. 
                       All expressions must be of the same type as 
                       test_expression.
Run Code Online (Sandbox Code Playgroud)

而不是IN,您可以使用JOIN两个字段:

SELECT U.* 
FROM user U
  INNER JOIN userType UT
    ON U.code = UT.code
    AND U.userType = UT.userType
Run Code Online (Sandbox Code Playgroud)


cdh*_*wie 9

你可以使用这样的表格:

select * from user u
where exists (select 1 from userType ut
              where u.code = ut.code
                and u.userType = ut.userType)
Run Code Online (Sandbox Code Playgroud)


Cai*_*ard 5

只有一些可怕的事情,比如

select * from user
where (code + userType) in ( select code + userType from userType )
Run Code Online (Sandbox Code Playgroud)

然后,您必须管理空值和连接数字,而不是添加它们和转换,以及代码 12 和用户类型 3 与代码 1 和用户类型 23,以及...

..这意味着您开始进入类似的情况:

--if your SQLS supports CONCAT
select * from user
where CONCAT(code, CHAR(9), userType) in ( select CONCAT(code, CHAR(9), userType) from ... )

--if no concat
select * from user
where COALESCE(code, 'no code') + CHAR(9) + userType in ( 
  select COALESCE(code, 'no code') + CHAR(9) + userType from ... 
)
Run Code Online (Sandbox Code Playgroud)

CONCAT 将对大多数事情进行字符串连接,并且如果一个元素为 NULL,则不会将整个输出压缩为 NULL。如果你没有 CONCAT 那么你将使用字符串 concat+但任何可能为空的东西都需要一个 COALESCE/ISNULL 。在任何一种情况下,你都需要像 CHAR(9) (一个制表符)这样的东西字段以防止它们混合。字段之间的东西应该是南向的,这在数据中不自然存在。

遗憾的是 SQLS 不支持这一点,而 Oracle 支持:

where (code, userType) in ( select code, userType from userType )
Run Code Online (Sandbox Code Playgroud)

但可能不值得切换数据库;我会使用 EXISTS 或 JOIN 来实现多列过滤器


所以你就可以了:一个不使用连接或存在的解决方案..以及一堆你不应该使用它的原因;)