PERSON
---------------------
ID NAME
1 ALEX
2 BOB
3 JAMES
PERSON_FRUIT
---------------------
PERSON_ID FRUIT_ID
1 1
2 1
3 2
FRUIT
---------------------
ID NAME
1 APPLE
2 ORANGE
如何编写查询,检查多人是否拥有相同的水果? 我需要一个查询,告诉我以下结果。
我试过使用以下查询
select
F.NAME
from
PERSON P1
join PERSON_FRUIT PF1 on P1.ID = PF1.PERSON_ID
join PERSON_FRUIT PF2 on PF1.FRUIT_ID = PF2.FRUIT_ID
join PERSON P2 on PF2.PERSON_ID = P2.ID
join FRUIT F on F.ID = PF1.FRUIT_ID
where
P1.ID = 1 and P2.ID = 2 and P1.ID <> P2.ID;
获取ALEX和BOB的共同成果,但此查询仅限2人传递。
答案 0 :(得分:0)
使用此查询,您需要将人员指定为ID列表(在WHERE
子句中),并且您需要指定给定的人员ID总数(在HAVING
子句中)。
SELECT F.Name
FROM person_fruit PF INNER JOIN fruit F ON PF.Fruit_ID = F.ID
WHERE PF.Person_ID IN (1,2,4) '<- List of person IDs'
GROUP BY PF.Fruit_ID
HAVING COUNT(Person_ID) = 3 '<- Total number of person IDs'