一个查询,以找到喜欢至少2的人

问题描述 投票:0回答:1

起初我被要求找到喜欢蓝眼睛的人很容易的人,然后我被要求找到喜欢至少2个绿眼睛的人,当我扩展我的第一个查询以解决第二个任务时,我的查询结果没有。

查询是在2个表上运行的(人和喜欢)人包含人,personB_id ==>人)

如果有人可以帮我写第二个查询,将不胜感激:)

在下面你可以找到我分别为第一个任务和第二个任务写的查询。

任务1:

SELECT distinct p1.name
FROM Persons as p1,Persons as p2, Likes as l 
where p1.id =l.personA_id
And p2.id = l.personB_id
And p2.eyeColor= "blue"

Tski:

SELECT distinct p1.name
FROM Persons as p1,Persons as p2, Likes as l, Persons as p3
where p1.id =l.personA_id
And p2.id = l.personB_id
And p3.id = l.personB_id
And p2.id = l.personB_id <> p3.id = l.personB_id
And p2.eyeColor= "green"
And p3.eyeColor= "green"
sql database self-join
1个回答
0
投票

我在想“分组”:

SELECT pa.name
FROM Likes l JOIN
     Persons pa
     ON pa.id = l.personA_id JOIN
     Persons pb
     ON pb.id = l.personB_id
WHERE pb.eyeColor = 'green'
GROUP BY pa.name, pa.id
HAVING COUNT(*) >= 2;

笔记:

  • 切勿在FROM条款中使用逗号。这是21世纪,这种语法已经过时了二十多年。
  • 始终使用正确,明确,标准的JOIN语法。
  • GROUP BY包括人员ID,以防两个人有相同的名字。
© www.soinside.com 2019 - 2024. All rights reserved.