子查询里有group by的时候,子查询条件无效,加上having的条件之后就可以,原因是什么

场景:通过group by去重

image-20210405164329533

遇到问题

合并之后结果为空

# 1 子查询 结果是(1,4)
select id from test GROUP BY name 
# 2 父查询 结果是(2,3)
select id from test 
where id not in (1,4)
# 3 合并 结果为空
select id from test 
where id not in 
    (select id from test GROUP BY name)

image-20210405174013683

image-20210405174054109

image-20210405174119931

image-20210405174211632

 

用explain查询一下,两个select type 不一样的

子查询中的group by没有走的 , 你可以尝试在id上加一个函数, 例如max(id) 这样就会让子查询走group by