考虑以下简化查询:
SELECT * FROM x, y JOIN z ON z.id = x.bean_id
它不起作用; MySQL(技术上是MariaDB 10.0.21)给出错误:
Unknown column 'x.bean_id' in 'on clause'
但是,如果我切换表引用的顺序(x, y
变为y, x
),则查询成功执行:
SELECT * FROM y, x JOIN z ON z.id = x.bean_id
这里发生了什么?
答案 0 :(得分:1)
通过在括号中包含x, y
隐式交叉连接,可以缓解您的即时错误:
SELECT * FROM (x, y) JOIN z ON z.id = x.bean_id
我认为该错误与关于y
所属的连接的歧义有关。
但是您将旧学校隐式连接语法与现代(和正确的)显式连接语法混合在一起。不要这样做,实际上根本不使用旧的连接语法。相反,始终使用显式连接:
SELECT *
FROM x
INNER JOIN y
ON x.id = y.id
INNER JOIN z
ON z.id = x.bean_id;
答案 1 :(得分:1)
代码看起来很可疑,x
和y
之间存在隐式联接:
SELECT * FROM y, x JOIN z ON z.id = x.bean_id
x
和y
之间是否缺少连接条件?
或者您是否打算在x
和y
之间进行交叉联接,并且纯粹根据z
加入条件?交叉连接是一种相对不寻常的连接。
如果是后者,我会重写查询以使其清楚,例如:
SELECT
*
FROM
x
CROSS JOIN
y
INNER JOIN
z
ON (z.id = x.bean_id)
以上内容与您说的当前代码完全相同。
或者,如果x
和y
之间的联接中缺少某个条件,则会采用以下形式:
SELECT
*
FROM
x
INNER JOIN
y
ON (/*INSERT MISSING JOIN EXPRESSION BETWEEN x AND y HERE*/)
INNER JOIN
z
ON (z.id = x.bean_id)
答案 2 :(得分:1)
是的,这很重要。
However, the precedence of the comma operator is less than that of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form Unknown column 'col_name' in 'on clause' may occur. Information about dealing with this problem is given later in this section.