我的任务是在表“联系人”表中的“联系人”和“联系人”列中查找“联系人”的二级连接数。到目前为止,我已经能够找到第二级联系人的姓名,但不能消除那些属于第一级联系人的名字。例如,如果Adam既是Mike的第二级连接又是Mike的一级连接,则查询不应返回Adam,但我的查询应该返回。我是SQL的新手,所以任何帮助都很棒。
SELECT
contactsB.contacter
FROM
contacts AS contactsB
INNER JOIN contacts AS contactsA
ON contactsA.contacter = contactsB.contactee
AND contactsA.contactee <> contactsB.contactee
AND contactsA.contactee = <insert contactee here>
最佳答案
使用此查询
SELECT b.contactee, c.contacter
FROM
contacts b
INNER JOIN contacts c ON b.contacter = c.contactee AND b.contactee != c.contacter
ORDER BY 1
要获取二级联系人,只需以这种方式添加
COUNT(*)
和GROUP BY
SELECT b.contactee, COUNT(*)
FROM
contacts b
INNER JOIN contacts c ON b.contacter = c.contactee AND b.contactee != c.contacter
GROUP BY 1
关于mysql - MySQL中的二级连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33032010/