我将给出一个我的意思的简单示例,但实质上我想要选择表中的所有条目,这些条目是该表的某些其他条目的正确子集。例如,这是一个表
+----+---------------+------------+
| id | name |department |
+----+---------------+------------+
| 1 | John Smith | 1 |
| 1 | John Smith | 2 |
| 2 | Sally Thomas | 3 |
| 2 | Sally Thomas | 4 |
| 3 | Jimmy John | 1 |
| 3 | Jimmy John | 2 |
| 3 | Jimmy John | 3 |
| 4 | Tom Roberts | 3 |
| 4 | Tom Roberts | 4 |
+----+---------------+------------+
从那张表中,我只想选择约翰史密斯。原因是约翰史密斯工作的部门完全被吉米约翰工作的部门所包含。莎莉托马斯工作的部门与汤姆罗伯茨的工作部门完全相同,所以他们不相互包含。我正在使用this定义适当的子集。我怎么能写一个SQL语句来涵盖这个?谢谢!
答案 0 :(得分:0)
select t1.name, t2.name
from t t1 join
t t2
on t1.department = t2.department join
(select name, count(*) as cnt
from t
group by name
) t1name
on t1.name = t1name.name join
(select name, count(*) as cnt
from t
group by name
) t2name
on t2.name = t2name.name
group by t1.name, t2.name
having count(*) = t2name.cnt and -- have everything in t2
t2name.cnt < t1name.cnt; -- strict subset
嗯,另一种方法使用group_concat()
:
select t1.name, t2.name
from t t1 join
t t2
on t1.department = t2.department
group by t1.name, t2.name
having group_concat(t2.department order by t2.department) =
(select group_concat(t.department order by t.department)
from t
where t.name = t2.department
);
答案 1 :(得分:0)