MySQL “Unknown Column in ON Clause” error: detailed explanation of connection order confusion
When encountering the "#1054 - Unknown column 'p.id' in 'on clause'" error in MySQL, the key is to understand the potential problems of mixing ANSI-89 and ANSI-92 style joins in the query. By default, MySQL evaluates connections based on their priority, which can lead to confusion if the connection order is not explicitly specified.
In an incorrect query, MySQL will interpret the query as follows, where comma-style joins are evaluated after the JOIN keyword join:
<code class="language-sql">FROM property p, ( propertygeometry pg JOIN shortlist sl ON sl.PropertyID = p.id AND sl.MemberID = 384216 ... )</code>
At this point, MySQL believes that table "p" has not been declared, causing an "unknown column" error.
To avoid this confusion, it is recommended to always use ANSI-92 style joins throughout the query, i.e. using the JOIN keyword:
<code class="language-sql">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</code>
With this approach, the connection sequence is clear, thus avoiding confusing error messages.
The above is the detailed content of Why Does MySQL Throw 'Unknown Column in ON Clause' When Mixing Join Styles?. For more information, please follow other related articles on the PHP Chinese website!