You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查询两个不同长度ID列表交集时结果异常,如何修正?

交集查询问题解答

你的SQL语句不正确

你写的exists子查询没有关联外部sval表的id字段,这个子查询只要能查到任意一条符合fid=3994 and val=0的记录,就会判定为true。因此外部查询会返回所有满足val='True' and fid=4044的id,最终计数和第一个查询完全一致,自然远大于第二个查询的结果数。

正确的交集查询写法

下面是几种能正确获取两个查询结果交集的写法:

方法1:关联exists子查询

修改exists子查询,添加id的关联条件,同时子查询用select 1更高效(exists仅判断存在性,无需返回具体字段):

select distinct(id) 
from sval 
where val = 'True' and fid = 4044
  and exists(
    select 1 from ival 
    where fid = 3994 and val=0
      and ival.id = sval.id
  );

方法2:使用IN子句

逻辑直观的写法,适合子查询结果集不大的场景:

select distinct(id) 
from sval 
where val = 'True' and fid = 4044
  and id in (
    select distinct(id) from ival 
    where fid = 3994 and val=0
  );

方法3:使用内连接(JOIN)

通过内连接直接筛选出两边都存在的id:

select distinct(sval.id)
from sval
inner join ival on sval.id = ival.id
where sval.val = 'True' and sval.fid = 4044
  and ival.fid = 3994 and ival.val = 0;

内容的提问来源于stack exchange,提问作者ifrj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:26:07