计数后的SQL查询公共值

时间:2015-11-12 04:52:23

标签: mysql sql database

我想知道如何解决这个问题,我有这两个表:

TABLE FRIENDSHIP
Name | Friend
--------------
John | Mark
Peter | Paul
Simon | Mary

TABLE SCHOOL
Name | School
--------------
John | SchoolA
Mark | SchoolA
Peter | SchoolB
Paul | SchoolC
Simon | SchoolC
Mary | SchoolD

如何选择那些朋友但不参加同一所学校的人? 我想选择计数为< 2的第一所学校,然后将这些人的名字与FRIENDSHIP表中的名字进行比较(比较两个名称和朋友的名字)。如何将其转换为查询?对不起是一个新手..

应该给我回复:

Name | Friend
---------------
Peter | Paul
Simon | Mary

感谢您的帮助

4 个答案:

答案 0 :(得分:1)

您可以尝试将SCHOOL表加入FRIENDSHIP两次,对于该对中的每个朋友一次。然后,您可以通过仅保留各自的学校相同的朋友对来限制您的结果集。

SELECT f.Name, f.Friend
FROM FRIENDSHIP f INNER JOIN SCHOOL s1 ON f.Name = s1.Name
INNER JOIN SCHOOL s2 ON f.Friend = s2.Name
WHERE s1.School <> s2.School

以下是使用您的示例数据进行此查询的工作演示:

SQLFiddle

答案 1 :(得分:0)

SELECT F.Name, F.Friend
FROM Friendship F
INNER JOIN School AS School1 ON F.Name = School1.Name
INNER JOIN School AS School2 ON F.Friend = School2.Name
WHERE School1.School <> School2.School

编辑:根据实际架构修改

SELECT C.Name, C.Colleague
FROM Collaboration C
INNER JOIN restaurant_founder AS rf1 ON C.Name = rf1.founder
INNER JOIN restaurant_founder AS rf2 ON C.Colleague = rf2.founder
WHERE rf1.restaurant <> rf2.restaurant

答案 2 :(得分:0)

你可以这样做:

select * from friend f
where (select s2.school from school s2
       where f.name = s2.name) != (select s1.school from school s1
                                  where f.friend = s1.name)

这是Demo

答案 3 :(得分:0)

您的示例中有两种类型的人。

我们将第一个称为Name,将第二个称为Friend

NameFriend都有School

我们需要比较他们的School是不同的,所以我们需要首先获得他们的School

School加入Name

,让Friend.Name获得School.Name
SELECT f.Name, School, f.Friend 
FROM Friend AS f
INNER JOIN School AS s ON f.Name = s.Name

现在,让School加入Friend

,让Friend.Friend获得School.Name
SELECT Friend, School 
FROM Friend AS f
INNER JOIN School AS s ON f.Friend = s.Name

现在我们得到了SchoolOfNameSchoolOfFriend的结果,让Friend SchoolOfNameFriend SchoolOfFriend

此外,School的{​​{1}}不应等于SchoolOfName的{​​{1}}

School