sql - MySQL ON 子句中的未知列

标签 sql mysql mysql-error-1054

我有以下 MySQL 查询:

SELECT p.*,
    IF(COUNT(ms.PropertyID) > 0,1,0) AS Contacted,
    pm.MediaID,
    date_format(p.AvailableFrom, '%d %b %Y') AS 'AvailableFrom',
    astext(pg.Geometry) AS Geometry
FROM property p, propertygeometry pg
    JOIN shortlist sl ON sl.PropertyID = p.id AND sl.MemberID = 384216
    LEFT JOIN message ms ON ms.PropertyID = p.id AND ms.SenderID = 384216
    LEFT JOIN property_media pm ON pm.PropertyID = p.id AND pm.IsPrimary = 1
WHERE p.paused = 0
    AND p.PropertyGeometryID = pg.id
GROUP BY p.id

我收到此错误:

#1054 - “on 子句”中存在未知列“p.id”

据我所知,查询看起来是正确的,知道可能出了什么问题吗?

最佳答案

不要混合使用 ANSI-89 样式和 ANSI-92 样式连接。它们具有不同的优先级,这可能会导致令人困惑的错误,这就是这里发生的情况。您的查询将被解释如下:

FROM property p, (
    propertygeometry pg
    JOIN shortlist sl ON sl.PropertyID = p.id AND sl.MemberID = 384216
    ...
)

在上面,在考虑逗号样式连接之前,首先评估使用 JOIN 关键字的连接。此时表 p 尚未声明。

来自MySQL manual :

However, the precedence of the comma operator is less than 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.

我建议始终使用 ANSI-92 样式连接,即使用 JOIN 关键字:

SELECT p.*,
    IF(COUNT(ms.PropertyID) > 0,1,0) AS Contacted,
    pm.MediaID,
    date_format(p.AvailableFrom, '%d %b %Y') AS 'AvailableFrom',
    astext(pg.Geometry) AS Geometry
FROM property p
    JOIN propertygeometry pg ON p.PropertyGeometryID = pg.id
    JOIN shortlist sl ON sl.PropertyID = p.id AND sl.MemberID = 384216
    LEFT JOIN message ms ON ms.PropertyID = p.id AND ms.SenderID = 384216
    LEFT JOIN property_media pm ON pm.PropertyID = p.id AND pm.IsPrimary = 1
WHERE p.paused = 0
GROUP BY p.id

相关:

关于sql - MySQL ON 子句中的未知列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615455/

相关文章:

SQL Server : Filter for only the rows directly after a row containing specific text

mysql - 有没有办法加速或替换 LIKE 搜索查询?

MySQL 错误 1054 : Unknown Column 'hotels.postal_code' in 'on clause'

sql - 相同外键的两列的 INNER JOIN

sql - 如何在 sql server 2005 中使用 sql 查询更改表中的列顺序?

mysql - SELECT all 如果参数为 null 否则返回特定项目 laravel

php - 添加where条件时mysql查询不起作用

mysql复制需要有两台master服务器

php - 如何检查数据库列中存在的字符串?

mysql - 字段列表中的未知列 MySql 存储过程