【问题标题】:MySQL get all rows in which one field belongs to array, and all members have a common value in the other fieldMySQL获取一个字段属于数组的所有行,并且所有成员在另一个字段中都有一个共同的值
【发布时间】:2012-12-24 01:25:12
【问题描述】:

假设我有以下用户属性表:

id, user_id  properties
1,  NULL,    prop_ss1
2,  NULL,    prop_ss2
3,  2,       prop_1
4,  2,       prop_2
5,  3,       prop_1
6,  3,       prop_2
7,  3,       prop_3
8,  4,       prop_1

给定一个 user_ids 数组,我如何获取 user_id 为 NULL 的所有属性的列表(如果您愿意,可以将其称为全局属性),或者在给定数组中的所有 user_ids 之间共享?

例如,给定一个数组 (2,3),我想得到:

prop_ss1
prop_ss2
prop_1
prop_2

或者,给定一个数组(2,3,4),我想得到:

prop_ss1
prop_ss2
prop_1

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    尝试两个独立查询的 UNION:

    SELECT properties FROM your_table WHERE user_id IS NULL
    
    UNION
    
    SELECT properties
    FROM your_table
    WHERE user_id IN (2, 3)
    GROUP BY properties
    HAVING COUNT(DISTINCT user_id) = 2
    

    在线查看:sqlfiddle

    最后一行中的数字2是您要查询的用户数。

    【讨论】:

      【解决方案2】:
      select distinct properties from table
      where user_id is null
      or user_id in (1,2,3)
      

      对不起,误读了您的帖子,需要分组并拥有

      【讨论】:

        猜你喜欢
        • 2016-09-19
        • 2017-03-28
        • 2014-06-23
        • 2020-03-06
        • 2022-08-22
        • 1970-01-01
        • 2021-12-01
        相关资源
        最近更新 更多