7

How to select people like apple and banana both from the data below?

table: MyTable

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

i.e in this case, P1, P2 should be the result.

I tried with

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

This is also resulting P3 because P3 also have apple.

Thanks for any help.

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Fahad Khan
  • 1,635
  • 4
  • 23
  • 37

5 Answers5

4
SELECT a.persons 
FROM MyTable a JOIN MyTable b on a.persons=b.persons 
WHERE a.fruit='Apple' and b.fruit='Banana'
Matt Healy
  • 18,033
  • 4
  • 56
  • 56
1

Try this:

SELECT persons 
FROM MyTable 
WHERE fruit IN ('Apple', 'Banana')
GROUP BY persons
HAVING COUNT(DISTINCT fruit) = 2;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
1

This would work:

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'
Uriil
  • 11,948
  • 11
  • 47
  • 68
0
select * from MyTable where fruit in("Apple") and persons in(select persons from MyTable where fruit in("Banana");
starko
  • 1,150
  • 11
  • 26
-1

Try this:

select persons from MyTable where fruit in("Apple","Banana");
DPenner1
  • 10,037
  • 5
  • 31
  • 46
saish
  • 1
  • 1