有两个表user
和user_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
...
一个集合总是恰好有四个属于它的用户。我想找到满足以下条件的用户集:
(用户编号由user.no_in_set
列标识。)
对于每个满足这些条件的集合,我想检索user1的名称。
答案 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