【问题标题】:Finding rows that have the same foreign key and members of the set satisfy a condition查找具有相同外键且集合成员满足条件的行
【发布时间】:2019-02-18 19:05:57
【问题描述】:

有两个表,useruser_set。这两个表都使用列id 作为它们的主键。

user 具有列 user_set_id 作为外键来指示它属于哪个用户集。

user表:

 id   | user_set_id  | name     | active | no_in_set         
------+--------------+----------+--------+------------
    1 |            1 | Alice    | t      | 3
    2 |            3 | Bob      | f      | 4
    3 |            2 | Charlie  | t      | 3
    4 |            2 | Daniel   | f      | 1
...

user_set表:

id   | name  
-----+--------
   1 | set1
   2 | set2
   3 | set3
... 

一个集合总是恰好有四个属于它的用户。我想找到满足以下条件的用户集:

  • user1 和 user2 处于活动状态
  • user3 和 user4 处于非活动状态

(用户编号由列user.no_in_set标识。)

对于满足这些条件的每个集合,我想检索 user1 的名称。

【问题讨论】:

  • 我已经更正了示例表中的错字,谢谢。
  • “活跃”是指“包含”吗?我会澄清您的问题,例如:“我希望找到所有集合:A)同时包含用户 1 和用户 2,B)不包含用户 3 和 4。也令人困惑:“我想检索 user1 的名称”。 user1不是爱丽丝吗?什么意思?

标签: sql postgresql


【解决方案1】:

嗯。我在考虑条件聚合:

select u.user_set_id
from user u
group by u.user_set_id
having bool_or( u.no_in_set = 1 and u.active) and
       bool_or( u.no_in_set = 2 and u.active) and
       bool_or( u.no_in_set = 3 and not u.active) and
       bool_or( u.no_in_set = 4 and not u.active) ;

【讨论】:

    【解决方案2】:

    您可以利用满足所有条件的集合正好有 4 行这一事实:

    SELECT user_set_id, name
    FROM user
    WHERE no_in_set = 1 
        AND user_set_id IN (
            SELECT user_set_id 
            FROM user
            WHERE (no_in_set = 1 AND active) 
                OR (no_in_set = 2 AND active) 
                OR (no_in_set = 3 AND NOT active) 
                OR (no_in_set = 4 AND NOT active) 
            GROUP BY user_set_id 
            HAVING count(*) = 4)
    ORDER BY user_set_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多