SQL进阶-exists函数
exists函数使用问题exists 和not exists使用过程中,出现exists为A表的全部值(not exists 出现的是空值)举例如下:SELECT a1.*FROM a a1WHERE not EXISTS -- 不存在满足以下条件的行(SELECT 1FROM a a2WHEREa2.gmv >100000000)查询出来的是a表的全部值问题出现在可能有2个方面:A表中存在
·
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
更多推荐
已为社区贡献1条内容
所有评论(0)