如何使用MySQL查询合适的子集?

时间:2016-11-08 02:39:21

标签: mysql sql database subset

我将给出一个我的意思的简单示例,但实质上我想要选择表中的所有条目,这些条目是该表的某些其他条目的正确子集。例如,这是一个表

+----+---------------+------------+
| 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语句来涵盖这个?谢谢!

2 个答案:

答案 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)

SELECT a.name
FROM (
    SELECT id,name,group_concat(dept) AS dept
    FROM tab
    GROUP BY id
) AS a
JOIN (
    SELECT id,name,group_concat(dept) AS dept
    FROM tab
    GROUP BY id
) AS b ON b.dept LIKE concat(a.dept,',%')

enter image description here