3

Here is the table

ID    WHO    FRUIT
1     Adam   Apple
2     Adam   Lemon
3     Eve    Apple
4     Adam   Grape
5     God    Papaya
6     Eve    Melon

How do I get all persons who have apple and lemon: in this case, so that I get the result Adam?

Furthermore, I want all persons who have apple and lemon or melon, so I would get Adam and Eve?

1 Answer 1

6

Use a self join on the table.

First one:

SELECT t1.who
FROM   table t1
JOIN   table t2
ON     t1.who = t2.who
WHERE
       t1.fruit = 'Apple'
AND    t2.fruit = 'Lemon'

Second one:

SELECT t1.who
FROM   table t1
JOIN   table t2
ON     t1.who = t2.who
WHERE
       t1.fruit = 'Apple'
AND    ( t2.fruit = 'Lemon' OR t2.fruit = 'Melon' )
Sign up to request clarification or add additional context in comments.

1 Comment

The t1.fruit != t2.fruit condition is rather implied by the next two conditions, in both queries. No harm done - but not much good either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.