开发者

MySQL select multiple values from column

开发者 https://www.devze.com 2022-12-13 23:33 出处:网络
Here is the table IDWHOFRUIT 1AdamApple 2AdamLemon 3EveApple 4AdamGrape 5GodPapaya 6 开发者_运维问答EveMelon

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?


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' )
0

精彩评论

暂无评论...
验证码 换一张
取 消