表引用的顺序在MySQL中是否重要?

时间:2017-12-27 04:00:05

标签: mysql sql mariadb

考虑以下简化查询:

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

这里发生了什么?

3 个答案:

答案 0 :(得分:1)

通过在括号中包含x, y隐式交叉连接,可以缓解您的即时错误:

SELECT * FROM (x, y) JOIN z ON z.id = x.bean_id

我认为该错误与关于y所属的连接的歧义有关。

Demo

但是您将旧学校隐式连接语法与现代(和正确的)显式连接语法混合在一起。不要这样做,实际上根本不使用旧的连接语法。相反,始终使用显式连接:

SELECT *
FROM x
INNER JOIN y
    ON x.id = y.id
INNER JOIN z
    ON z.id = x.bean_id;

答案 1 :(得分:1)

代码看起来很可疑,xy之间存在隐式联接:

SELECT * FROM y, x JOIN z ON z.id = x.bean_id

xy之间是否缺少连接条件?

或者您是否打算在xy之间进行交叉联接,并且纯粹根据z加入条件?交叉连接是一种相对不寻常的连接。

如果是后者,我会重写查询以使其清楚,例如:

SELECT
    *

FROM 
    x 

CROSS JOIN
    y

INNER JOIN 
    z 
    ON (z.id = x.bean_id)

以上内容与您说的当前代码完全相同。

或者,如果xy之间的联接中缺少某个条件,则会采用以下形式:

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.

请参阅https://dev.mysql.com/doc/refman/5.7/en/join.html了解更多详情。

顺便说一下,你为什么用x,y,z代表你的情况,但是错误信息是orignal column name'bean_id'?