2

我有一个包含 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,因此可以有单独的较小查询。

4

1 回答 1

2

这似乎适用于 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
于 2013-04-24T13:21:49.313 回答