MySQL同一列多逻辑组合查询返回结果错误排查求助
核心问题是SQL逻辑运算符优先级错误
SQL中AND的运算优先级高于OR,你没有对需要组合的条件加括号,导致实际执行的逻辑和预期完全不符。
你写的内层条件:
where `wp_laravel_reserved_0`.`user_id` = `wp_push_notification_topics`.`user_id` and `topic_name` = 'all' or exists(/* 订阅so2的判断 */)
实际会被SQL解析为:
where ( `wp_laravel_reserved_0`.`user_id` = `wp_push_notification_topics`.`user_id` and `topic_name` = 'all' ) or exists(/* 订阅so2的判断 */)
这就导致只要用户订阅了so2,不管有没有满足前面的订阅all的条件,整个判断都会返回真,所以你把all改成all22之后结果完全没有变化。
修正方案
首先给需要组合的(all || so2)逻辑加上括号,保证运算顺序符合预期:
select * from `wp_push_notification_topics` where exists( select * from `wp_push_notification_topics` as `wp_laravel_reserved_0` where `wp_push_notification_topics`.`user_id` = `wp_laravel_reserved_0`.`user_id` and `topic_name` = 'so' and exists( select * from `wp_push_notification_topics` where `wp_laravel_reserved_0`.`user_id` = `wp_push_notification_topics`.`user_id` and ( `topic_name` = 'all' or exists( select * from `wp_push_notification_topics` as `wp_laravel_reserved_1` where `wp_push_notification_topics`.`user_id` = `wp_laravel_reserved_1`.`user_id` and `topic_name` = 'so2' ) ) ) )
另外也可以用GROUP BY + HAVING的写法,逻辑更清晰,避免多层嵌套子查询的可读性问题:
-- 对应你描述的 so && (all || so2) 逻辑 select user_id from `wp_push_notification_topics` group by user_id having sum(`topic_name` = 'so') > 0 and (sum(`topic_name` = 'all') > 0 or sum(`topic_name` = 'so2') > 0)
内容的提问来源于stack exchange,提问作者Steve Moretz
相关产品推荐
相关产品推荐

