在您的查询中,首先评估 FROM 子句。这具有从查询的其余部分隐藏表“a”的效果。(同样的规则也适用于列别名。)
我拼凑了一些无意义的表格进行演示。此查询有效。
SELECT *
FROM
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABCs
LEFT OUTER JOIN
(X JOIN W on X.x_id=W.w_id
JOIN Z on W.w_id=Z.z_id) AS XYZs on ABCs.a_id=XYZs.w_id
但是这个在 SELECT 子句中引用 A.a_id 的不是。
SELECT A.a_id, *
FROM
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABCs
LEFT OUTER JOIN
(X JOIN W on X.x_id=W.w_id
JOIN Z on W.w_id=Z.z_id) AS XYZs on ABCs.a_id=XYZs.w_id
ERROR: invalid reference to FROM-clause entry for table "a"
LINE 1: SELECT A.a_id, *
^
HINT: There is an entry for table "a", but it cannot be referenced from
this part of the query.
改为通过您为连接表达式提供的别名来引用它。
SELECT ABCs.a_id, *
FROM
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABCs
LEFT OUTER JOIN
(X JOIN W on X.x_id=W.w_id
JOIN Z on W.w_id=Z.z_id) AS XYZs on ABCs.a_id=XYZs.w_id
要使用相同的连接表达式两次,请使用两个不同的别名。
SELECT *
FROM
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABC_1s
LEFT OUTER JOIN
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABC_2s on ABC_1s.a_id=ABC_2s.c_id
如果需要,请在 SELECT 子句中使用相同的语法 alias_name.column_name。
SELECT ABC_1s.a_id, ABC_2s.a_id, *
FROM
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABC_1s
LEFT OUTER JOIN
(A JOIN B ON A.a_id =B.b_id
JOIN C on B.b_id=C.c_id) AS ABC_2s on ABC_1s.a_id=ABC_2s.c_id