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


当前回答

Postgres SQL  : version 9.6
Total records on tables : mjr_agent = 145, mjr_transaction_item = 91800

1.使用EXISTS[平均查询时间:1.42s]

SELECT count(txi.id) 
FROM 
mjr_transaction_item txi
WHERE 
EXISTS ( SELECT 1 FROM mjr_agent agnt WHERE agnt.agent_group = 0 AND (txi.src_id = agnt.code OR txi.dest_id = agnt.code) ) 

2.使用两行IN子句[平均查询时间:0.37s]

SELECT count(txi.id) FROM mjr_transaction_item txi
WHERE 
txi.src_id IN ( SELECT agnt.code FROM mjr_agent agnt WHERE agnt.agent_group = 0 ) 
OR txi.dest_id IN ( SELECT agnt.code FROM mjr_agent agnt WHERE agnt.agent_group = 0 )

3.使用inner JOIN模式[平均查询时间:2.9s]

SELECT count(DISTINCT(txi.id)) FROM mjr_transaction_item txi
INNER JOIN mjr_agent agnt ON agnt.code = txi.src_id OR agnt.code = txi.dest_id
WHERE 
agnt.agent_group = 0

所以,我选择了第二种选择。

其他回答

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

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

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

我觉得这样更容易

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 * 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 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

为什么使用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.*。