我需要在SQL Server中实现以下查询:

select *
from table1
WHERE  (CM_PLAN_ID,Individual_ID)
IN
(
 Select CM_PLAN_ID, Individual_ID
 From CRM_VCM_CURRENT_LEAD_STATUS
 Where Lead_Key = :_Lead_Key
)

但是WHERE..IN子句只允许1列。我如何比较2个或更多的列与另一个内部选择?


当前回答

select * from tab1 where (col1,col2) in (select col1,col2 from tab2)

注意: Oracle忽略一个或多个所选列为NULL的行。在这些情况下,你可能想要使用NVL-Funktion将NULL映射到一个特殊的值(不应该在值中);

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

其他回答

select * from tab1 where (col1,col2) in (select col1,col2 from tab2)

注意: Oracle忽略一个或多个所选列为NULL的行。在这些情况下,你可能想要使用NVL-Funktion将NULL映射到一个特殊的值(不应该在值中);

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

我觉得这样更容易

Select * 
from table1 
WHERE  (convert(VARCHAR,CM_PLAN_ID) + convert(VARCHAR,Individual_ID)) 
IN 
(
 Select convert(VARCHAR,CM_PLAN_ID) + convert(VARCHAR,Individual_ID)
 From CRM_VCM_CURRENT_LEAD_STATUS 
 Where Lead_Key = :_Lead_Key 
) 

希望这对你有所帮助:)

如果你想要一个表,然后使用以下查询

SELECT S.* 
FROM Student_info S
  INNER JOIN Student_info UT
    ON S.id = UT.id
    AND S.studentName = UT.studentName
where S.id in (1,2) and S.studentName in ('a','b')

并表中数据如下

id|name|adde|city
1   a   ad  ca
2   b   bd  bd
3   a   ad  ad
4   b   bd  bd
5   c   cd  cd

然后输出如下

id|name|adde|city
1   a   ad  ca
2   b   bd  bd

简单的EXISTS子句是最干净的

select *
from table1 t1
WHERE
EXISTS
(
 Select * --or 1. No difference...
 From CRM_VCM_CURRENT_LEAD_STATUS Ex
 Where Lead_Key = :_Lead_Key
-- correlation here...
AND
t1.CM_PLAN_ID = Ex.CM_PLAN_ID AND t1.CM_PLAN_ID =  Ex.Individual_ID
)

如果相关性中有多行,那么JOIN会在输出中给出多行,因此需要distinct。这通常使EXISTS更有效。

注意带有JOIN的SELECT *还包括行限制表中的列

查询:

select ord_num, agent_code, ord_date, ord_amount
from orders
where (agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders 
GROUP BY agent_code);

上面的查询在mysql中为我工作。 参考下面的链接——>

https://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php