我需要在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个或更多的列与另一个内部选择?


当前回答

简单的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 *还包括行限制表中的列

其他回答

你可以从子查询中创建一个派生表,并将table1连接到这个派生表:

select * from table1 LEFT JOIN 
(
   Select CM_PLAN_ID, Individual_ID
   From CRM_VCM_CURRENT_LEAD_STATUS
   Where Lead_Key = :_Lead_Key
) table2
ON 
   table1.CM_PLAN_ID=table2.CM_PLAN_ID
   AND table1.Individual=table2.Individual
WHERE table2.CM_PLAN_ID IS NOT NULL

简单而错误的方法是使用+或连接两列并生成一列。

Select *
from XX
where col1+col2 in (Select col1+col2 from YY)

这会偏离轨道,很慢。不能在编程中使用,但如果你只是查询验证一些东西可能会被使用。

为什么使用WHERE EXISTS或DERIVED表,当你可以只做一个普通的内部连接:

SELECT t.*
FROM table1 t
INNER JOIN CRM_VCM_CURRENT_LEAD_STATUS s
    ON t.CM_PLAN_ID = s.CM_PLAN_ID
    AND t.Individual_ID = s.Individual_ID
WHERE s.Lead_Key = :_Lead_Key

如果(CM_PLAN_ID, Individual_ID)在状态表中不是唯一的,则可能需要使用SELECT DISTINCT t.*。

我觉得这样更容易

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 
) 

希望这对你有所帮助:)

简单的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 *还包括行限制表中的列