mysql 同一列上的多个条件
mysql multiple conditions on the same column
我有一个 table,它将用户和访客的订阅保存到 topic_names。
这是示例,现在我需要支持一堆复杂的查询,例如 get all the users who are subscribed to 'so' and 'all' or are subscribed to 'so2'
简而言之:so && (all || so2)
我首先尝试通过 having clause
进行操作,但看起来像在这种情况下,同一列不起作用,所以我想出了这个:
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')))
效果很好。
但即使我改变:
and `topic_name` = 'all'
到
and `topic_name` = 'all22'
我得到这个结果:
这显然与之前的结果完全一致,因此是错误的! user_id 不能包含 2 行,这意味着我做错了,请帮助。
如果在 HAVING
子句中正确设置条件,则可以通过聚合获得 user_id
s:
SELECT user_id
FROM wp_push_notification_topics
GROUP BY user_id
HAVING SUM(topic_name = 'so') > 0 AND SUM(topic_name IN ('all', 'so2')) > 0;
如果您想限制条件,使用户不订阅 'so'、'all' 和 'so2' 以外的任何内容,您可以添加到 HAVING
子句:
AND SUM(topic_name NOT IN ('so', 'all', 'so2')) = 0
如果你想要 table 的所有行:
SELECT *
FROM wp_push_notification_topics
WHERE user_id IN (
SELECT user_id
FROM wp_push_notification_topics
GROUP BY user_id
HAVING SUM(topic_name = 'so') > 0 AND SUM(topic_name IN ('all', 'so2')) > 0
);
我有一个 table,它将用户和访客的订阅保存到 topic_names。
这是示例,现在我需要支持一堆复杂的查询,例如 get all the users who are subscribed to 'so' and 'all' or are subscribed to 'so2'
简而言之:so && (all || so2)
我首先尝试通过 having clause
进行操作,但看起来像在这种情况下,同一列不起作用,所以我想出了这个:
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')))
效果很好。
但即使我改变:
and `topic_name` = 'all'
到
and `topic_name` = 'all22'
我得到这个结果:
这显然与之前的结果完全一致,因此是错误的! user_id 不能包含 2 行,这意味着我做错了,请帮助。
如果在 HAVING
子句中正确设置条件,则可以通过聚合获得 user_id
s:
SELECT user_id
FROM wp_push_notification_topics
GROUP BY user_id
HAVING SUM(topic_name = 'so') > 0 AND SUM(topic_name IN ('all', 'so2')) > 0;
如果您想限制条件,使用户不订阅 'so'、'all' 和 'so2' 以外的任何内容,您可以添加到 HAVING
子句:
AND SUM(topic_name NOT IN ('so', 'all', 'so2')) = 0
如果你想要 table 的所有行:
SELECT *
FROM wp_push_notification_topics
WHERE user_id IN (
SELECT user_id
FROM wp_push_notification_topics
GROUP BY user_id
HAVING SUM(topic_name = 'so') > 0 AND SUM(topic_name IN ('all', 'so2')) > 0
);