【问题标题】:mysql multiple conditions on the same columnmysql 在同一列上有多个条件
【发布时间】:2023-03-26 20:20:02
【问题描述】:

我有一个表,它将用户和客人的订阅保存到 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 行,这意味着我做错了,请帮忙。

【问题讨论】:

    标签: mysql group-by sum boolean-logic having


    【解决方案1】:

    如果您在HAVING 子句中正确设置条件,则可以通过聚合获得user_ids:

    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
    

    如果你想要表格的所有行:

    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
    );
    

    【讨论】:

    • 这太棒了,从来没有见过 sum 用于此目的,谢谢一个简单的问题,但是,在一个更复杂的例子中:so && (all || so2 && (something || something_else)) 有没有办法也支持这个更复杂的查询? (我正在寻找具有嵌套支持的通用解决方案,而不是针对特定示例的解决方案)
    • @stevemoretz 如果您正确使用布尔运算符,您可以根据需要设置条件。您的示例不清楚,因为 AND 运算符的优先级高于 OR 运算符。你可以这样做:HAVING SUM(topic_name = 'so') > 0 AND SUM(topic_name IN ('all', 'so2')) > 0 AND SUM(topic_name IN (something, something_else)) > 0HAVING SUM(topic_name = 'so') > 0 AND (SUM(topic_name IN ('all', 'so2')) > 0 OR SUM(topic_name IN (something, something_else)) > 0)
    • 就是这样,我使用了错误的语法,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多