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


当前回答

以某种形式将列连接在一起是一种“hack”,但是当产品不支持多个列的半连接时,有时您别无选择。

内部/外部连接解决方案不工作的例子:

select * from T1 
 where <boolean expression>
   and (<boolean expression> OR (ColA, ColB) in (select A, B ...))
   and <boolean expression>
   ...

当查询在本质上并不简单时,有时您无法访问基表集来执行常规的内/外连接。

如果你确实使用了这个“黑客”,当你组合字段时,请确保在它们之间添加足够的分隔符以避免误解,例如ColA + ":-:" + ColB

其他回答

取而代之的是使用WHERE EXISTS语法。

SELECT *
FROM table1
WHERE EXISTS (SELECT *
              FROM table2
              WHERE Lead_Key = @Lead_Key
                        AND table1.CM_PLAN_ID = table2.CM_PLAN_ID
                        AND table1.Individual_ID = table2.Individual_ID)

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

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

我们可以简单地这么做。

   select *
   from 
    table1 t, CRM_VCM_CURRENT_LEAD_STATUS c
    WHERE  t.CM_PLAN_ID = c.CRM_VCM_CURRENT_LEAD_STATUS
    and t.Individual_ID = c.Individual_ID

你可以从子查询中创建一个派生表,并将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

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