选择喜欢苹果和香蕉的人

时间:2014-12-23 08:30:50

标签: mysql sql select group-by having

如何从以下数据中选择像苹果和香蕉这样的人?

表:MyTable

persons |  fruit
-----------------------------
   P1       Apple
   P1       Banana
   P1       Mango
   P2       Banana
   P2       Apple
   P3       Mango   
   P3       Apple  

即在这种情况下,P1,P2应该是结果。

我试过

select * from MyTable where fruit in("Apple","Banana");

这也是P3的结果,因为P3也有苹果。

感谢您的帮助。

5 个答案:

答案 0 :(得分:4)

SELECT a.persons 
FROM MyTable a JOIN MyTable b on a.persons=b.persons 
WHERE a.fruit='Apple' and b.fruit='Banana'

答案 1 :(得分:1)

试试这个:

SELECT persons 
FROM MyTable 
WHERE fruit IN ('Apple', 'Banana')
GROUP BY persons
HAVING COUNT(DISTINCT fruit) = 2;

答案 2 :(得分:1)

这样可行:

SELECT distinct `t1`.`persons` FROM MyTable AS `t1`
INNER JOIN MyTable AS `t2` ON `t1`.`persons` = `t2`.`persons`
WHERE `t1`.`fruit` = 'Banana' AND `t2`.`fruit` = 'Apple'

答案 3 :(得分:0)

select * from MyTable where fruit in("Apple") and persons in(select persons from MyTable where fruit in("Banana");

答案 4 :(得分:-1)

试试这个:

select persons from MyTable where fruit in("Apple","Banana");