是否可以在IN
子句中包含多个字段?如下所示:
select * from user
where code, userType in ( select code, userType from userType )
我正在使用ms sql server 2008
我知道这可以通过连接和存在来实现,我只是想知道是否可以使用IN
子句来完成。
答案 0 :(得分: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.
而不是IN
,您可以使用JOIN
使用两个字段:
SELECT U.*
FROM user U
INNER JOIN userType UT
ON U.code = UT.code
AND U.userType = UT.userType
答案 1 :(得分:9)
你可以使用这样的表格:
select * from user u
where exists (select 1 from userType ut
where u.code = ut.code
and u.userType = ut.userType)
答案 2 :(得分:4)
只有可怕的东西,比如
select * from user
where (code + userType) in ( select code + userType from userType )
然后你必须管理空值和连接数字,而不是添加和转换,代码为12,用户类型为3,代码为1,用户类型为23,...
所以你去了:一个没有使用连接或存在的解决方案..以及为什么你不应该使用它的一些原因;)
答案 3 :(得分:0)
相反如何:
SELECT user.* FROM user JOIN userType on user.code = userType.code AND user.userType = userType.userType
答案 4 :(得分:0)
您可以使用联接
SELECT * FROM user U
INNER JOIN userType UT on U.code = UT.code
AND U.userType = UT.userType
答案 5 :(得分:0)
我必须做一些非常相似的事情,但EXISTS在我的情况下不起作用。这对我有用:
UPDATE tempFinalTbl
SET BillStatus = 'Non-Compliant'
WHERE ENTCustomerNo IN ( SELECT DISTINCT CustNmbr
FROM tempDetailTbl dtl
WHERE dtl.[Billing Status] = 'NEEDS FURTHER REVIEW'
AND dtl.CustNmbr = ENTCustomerNo
AND dtl.[Service] = [Service])
AND [Service] IN ( SELECT DISTINCT [Service]
FROM tempDetailTbl dtl
WHERE dtl.[Billing Status] = 'NEEDS FURTHER REVIEW'
AND dtl.CustNmbr = ENTCustomerNo
AND dtl.[Service] = [Service])
编辑:现在我看,这非常接近@ v1v3kn的回答
答案 6 :(得分:-2)
我不认为查询是非常便携的,使用像
这样的东西会更安全select * from user
where code in ( select code from userType ) and userType in (select userType from userType)
答案 7 :(得分:-3)
select * from user
where (code, userType) in ( select code, userType from userType );