sql - ON子句中的MySQL未知列

我有以下 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 clause' 中的未知列 '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

相关:

  • Why isn't SQL ANSI-92 standard better adopted over ANSI-89?

https://stackoverflow.com/questions/4065985/

相关文章:

mysql - 什么是 MySQL "Key Efficiency"

mysql - 在 MySQL 中生成整数序列

mysql - MySQL中的case语句

mysql - 在 MySQL 中循环遍历结果集

mysql - SQL唯一varchar区分大小写问题

mysql - 等于 (=) 和具有一个文字值的 IN 之间的性能差异

c# - MySQL - 实体 : The value for column 'IsPrimaryK

mysql - 如何更改 mysql 表列的默认值?

mysql - 用大量测试数据填充数据库表

mysql - 在 Rails 迁移 (MySQL) 中,您能否指定新列的位置?