我有两个问题:
SELECT g.id FROM "group" g INNER JOIN group_role gr on g.id = gr.group_fk
INNER JOIN role_details rd on rd.group_role_fk = gr.id
INNER JOIN mandate m on m.role_details_fk = rd.id where m.id = x
和
SELECT p.id, p.name, g.name, g.id
FROM person p INNER JOIN position pos on p.id = pos.person_fk
INNER JOIN role_details rd on rd.id = pos.role_details_fk
INNER JOIN group_role gr on gr.id = rd.group_role_fk
INNER JOIN "group" g on g.id = gr.group_fk
WHERE g.id = y
我希望能够将g.id传递给第二个查询,以便对于给定的" x",我得到p.id,p.name,g.name,g.id返回。我怎样才能做到这一点?可以通过更多连接来完成吗?
答案 0 :(得分:1)
你可以像这样嵌套你的查询,称为子查询,假设两个查询都有效,子查询只返回一个值。
SELECT p.id, p.name, g.name, g.id
FROM person p INNER JOIN position pos on p.id = pos.person_fk
INNER JOIN role_details rd on rd.id = pos.role_details_fk
INNER JOIN group_role gr on gr.id = rd.group_role_fk
INNER JOIN "group" g on g.id = gr.group_fk
WHERE g.id = (SELECT g.id FROM "group" g INNER JOIN group_role gr on g.id = gr.group_fk
INNER JOIN role_details rd on rd.group_role_fk = gr.id
INNER JOIN mandate m on m.role_details_fk = rd.id where m.id = x)
答案 1 :(得分:0)
最简单的方法是使用像
这样的子查询SELECT p.id, p.name, g.name, g.id
FROM person p INNER JOIN position pos on p.id = pos.person_fk
INNER JOIN role_details rd on rd.id = pos.role_details_fk
INNER JOIN group_role gr on gr.id = rd.group_role_fk
INNER JOIN "group" g on g.id = gr.group_fk
WHERE g.id IN (SELECT g2.id FROM "group" g2 INNER JOIN group_role gr on g2.id = gr.group_fk
INNER JOIN role_details rd on rd.group_role_fk = gr.id
INNER JOIN mandate m on m.role_details_fk = rd.id where m.id = x)
请小心在子查询中使用不同的别名,除非您想要在外部查询中查找您正在查看的确切行。
要避免使用子查询,可以使用更多连接重新构造查询 - 可能使用不同的别名多次连接同一个表。根据DBMS,这可能会获得一些性能。