sql语句中not in 不好使的原因之一

场景说明:查询某表中的某字段的值没有在另外一个表中对应的字段中出现过

比如现在有两个表,一个产品表product,一个优惠券批次表coupon,coupon中的product_code字段与product中的product_code形成一对一 的关系,现在有需求查询未绑定过的产品信息

一开始not exists搞,但是查了半天没搞懂,退而求其次,想用not in查询,发现查不出来,不好使。。。。但是in是好使的,于是查网上说使用not in可能会出现其他结果,至于原因,他没写....不靠谱啊

先观察此段sql:
select distinct product_code from coupon;

发现有一列为null,于是想是不是null的问题,于是有如下sql:

select product_code from product where product_code not in(select distinct product_code from coupon where product is not null);

运行后,好使了...

又考虑使用in会影响效率,于是改成如下sql:

select product_code from product pro left jion coupon cou on pro.product_code=cou.product_code where cou.product_code is null;

问题解决,原因,当使用左连接时,如果pro.product_code=cou.product_code没有成立的话,连接形成的总表属于coupon的全为null,所以可以使用如上语句

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值