我有一个包含2个表的数据库:人员和连接。 Connections具有person_id外键和connection_id外键。
我需要的是选择给定人员的连接连接(第3级连接),其中至少2个第2级连接具有第3级连接作为其连接。不应包括原始人的第一级连接。
我已尝试嵌套where子句,但只能选择所有第3级连接。
我的最后一次尝试有错误(可能已关闭):
SELECT * FROM `people` WHERE `id` =
ANY(SELECT `connection_id`, COUNT(*)
FROM `people_connections` WHERE `person_id` = 7)
我正在使用OO PHP,因此可以使用单独的较小查询。
答案 0 :(得分:1)
这似乎适用于SQLFiddle来获取所需的第三个连接的people.id。
http://www.sqlfiddle.com/#!2/9d32c/4
SELECT d.connect_id
FROM people_connections c
INNER JOIN people_connections d ON c.connect_id = d.person_id AND d.connect_id <> c.person_id
WHERE c.person_id = @yourIdHere
GROUP BY d.connect_id
HAVING COUNT(*) >= 2
没有JOINS的方式:
SELECT connect_id
FROM people_connections
WHERE person_id <> @yourIdHere AND
person_id IN (SELECT connect_id
FROM people_connections
WHERE person_id = @yourIdHere)
GROUP BY connect_id
HAVING COUNT(*) >= 2