怎么样的人拥有所有的东西? MySQL的

时间:2015-03-28 15:58:24

标签: mysql

下面是表格

person  things
A   TV
A   CAR
A   MOBILE
A   HOUSE
B   TV
C   TV
C   CAR
C   MOBILE
C   HOUSE
D   TV
E   TV
F   TV

以上我可以看到A和C拥有所有的东西。

根据我能够找到的书籍示例 每个人都有什么?使用以下查询,

SELECT things
FROM tbl_happiness as x 
WHERE NOT EXISTS 
( 
SELECT person 
FROM tbl_happiness as y 
WHERE NOT EXISTS 
( 
SELECT 1
FROM tbl_happiness as z 
WHERE z.person = y.person 
AND z.things = x.things
 )
);

是否可以使用相同的查询和别名更改来查找

哪个人拥有所有的东西?

3 个答案:

答案 0 :(得分:2)

我接近这些" set-within-sets"使用group byhaving的查询:

select person
from table t
group by person
having count(distinct thing) = (select count(distinct thing) from table t);

如果没有重复项,您可以使用:

having count(*) = (select count(distinct thing) from table t);

答案 1 :(得分:0)

SELECT person 
FROM tbl_happiness 
group by person
having count(distinct things) = (select count(distinct things) from tbl_happiness)

答案 2 :(得分:0)

效率可能较低,但很高兴看到......

SELECT x.*
  FROM my_table x
  LEFT
  JOIN 
     ( SELECT DISTINCT a.person 
                  FROM my_table a 
                  JOIN my_table b 
                  LEFT 
                  JOIN my_table c 
                    ON c.person = a.person 
                   AND c.thing = b.thing 
                 WHERE c.person IS NULL
     ) y
    ON y.person = x.person
 WHERE y.person IS NULL;