SQL咨询:如何用首个查询的客户结果集限定第二个查询的取值范围
可直接落地的实现方案
先给你吃个定心丸:你要实现的“先筛出目标客户的账户列表、再匹配对应的交易数据”的需求,是SQL最常见的关联查询场景,完全可行,下面两个方案都是适配你现有写法的,新手也能直接跑通,不需要记复杂语法:
方案1:最小改动适配你原本的IN写法
你代码里where test_cash_trans.client_acc in --- result of first query的位置,直接把第一个查询的结果作为子查询嵌入即可,注意两个细节:
- 子查询只需要返回和
IN匹配的字段(也就是client_acc),不需要冗余返回其他字段 - 子查询要保留第一个查询的全部过滤逻辑,也就是
client_id = 'LOG0000240'的条件
对应调整后的可运行代码:
--select transaction data for list of client generated in first query Select client_id, test_cash_trans.client_acc, sub_trans_type, settle_date, dbt_crt, test_cash_trans.currency, cash_amount, test_cash_trans.last_update From test_cash_trans inner join client_crm on test_cash_trans.client_acc = client_crm.client_acc -- 嵌入第一个查询的结果作为IN的判断依据 where test_cash_trans.client_acc in ( select client_acc from client_crm where client_id = 'LOG0000240' ) -- 提示:如果没有sum/count/avg这类聚合计算需求,这里的group by属于冗余代码 -- 不仅会拖慢查询速度,还可能在开启严格模式的数据库上报错,可按需删除 group by client_id, test_cash_trans.client_acc, sub_trans_type, settle_date, dbt_crt, test_cash_trans.currency, cash_amount, test_cash_trans.last_update
方案2:更高效的极简写法(推荐)
你当前的SQL已经将test_cash_trans和client_crm通过client_acc做了内连接,完全不需要单独拆分两次查询、再做结果传递,直接把第一个查询的过滤条件加到现有查询里,一步就能拿到全部结果,执行效率比嵌子查询更高:
Select client_crm.client_id, -- 明确指定字段来源,避免同名字段引发的歧义报错 test_cash_trans.client_acc, sub_trans_type, settle_date, dbt_crt, test_cash_trans.currency, cash_amount, test_cash_trans.last_update From test_cash_trans inner join client_crm on test_cash_trans.client_acc = client_crm.client_acc -- 直接加客户维度的过滤,等价于先筛出目标客户的所有账户,再匹配关联交易 where client_crm.client_id = 'LOG0000240'
新手易踩的两个常见坑
- 多表关联查询时,如果两个表存在同名字段(比如本例中的
client_id、client_acc),一定要明确标注字段所属的表名,不然数据库会因为分不清字段来源抛出语法错误 - 没有聚合计算需求时不要随手加
group by,如果只是要去除完全重复的行,直接在select后加distinct关键字即可,避免不必要的性能损耗。
内容的提问来源于stack exchange,提问作者Nelboy13
相关产品推荐
相关产品推荐

