查找具有相同外键且集合中的成员满足条件的行

时间:2019-02-18 19:05:58

标签: sql postgresql

有两个表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的名称。

2 个答案:

答案 0 :(得分:0)

嗯。我在考虑条件聚合:

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

答案 1 :(得分:0)

您可以利用一个事实,即满足所有条件的集合将恰好有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