exists函数使用问题
exists 和not exists使用过程中,出现exists为A表的全部值(not exists 出现的是空值)
举例如下:
SELECT a1.*
FROM a a1
WHERE not EXISTS -- 不存在满足以下条件的行
(SELECT 1
FROM a a2
WHERE a2.gmv >100000000)
查询出来的是a表的全部值
问题出现在可能有2个方面:
A表中存在空值行—该项情况,本次查询中不存在
A表和子查询没有做连接约束–注意,唯一值
修正后的:使用唯一值约束:
SELECT a1.*
FROM a a1
WHERE not EXISTS -- 不存在满足以下条件的行
(SELECT 1
FROM a a2
WHERE a1.year_month= a2.year_month
and 1= case when a2.gmv >100000000 then 1 else 0 end)
注意:如果约束的并非是唯一值,会出现数据错误的情况
结论:
exists 子查询
子查询的过程中注意在where限制条件中加入与A表的约束条件
参考sql 进阶中的1.8中
select uid
from testscores ts1
where subject in('maths','chinese')
and exists(select * from testscores ts2
where ts2.uid = ts1.uid
and 1= (case when subject ='maths' and scores>80 then 1
when subject ='chinese' and scores>50 then 1
else 0 end))
group by 1
having count(*) =2
博客探讨了在SQL查询中使用EXISTS和NOT EXISTS子查询时遇到的问题及其解决方法。当子查询没有与主查询进行有效约束时,可能会导致不期望的结果。文章提供了一个修正后的查询示例,强调在WHERE子句中加入与主表的约束条件以确保正确性。此外,还展示了如何使用CASE语句在子查询中进行条件判断。
1940





