Home >Database >Mysql Tutorial >Why am I getting an 'Unknown column 'p.id' in 'on clause'' error in my MySQL query?
"Unknown column" error in MySQL query
In MySQL, you may encounter an "Unknown column 'p.id' in ON clause" error when executing queries involving joins. To understand the cause of this error, let's delve into the query and its database interpretation.
Query explanation:
The query in question looks like this:
<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, 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</code>
This error is due to mixing ANSI-89 and ANSI-92 style joins, which can lead to ambiguity. In ANSI-89 syntax, joins are represented by commas, while in ANSI-92, the JOIN keyword is used.
Error description:
The database interprets the query as follows:
<code class="language-sql">FROM property p, ( propertygeometry pg JOIN shortlist sl ON sl.PropertyID = p.id AND sl.MemberID = 384216 ... )</code>
In this interpretation, table p is not declared before the comma-separated join with propertygeometry pg. Therefore, the database cannot find column p.id when evaluating the ON condition in subsequent joins.
Solution:
To work around this error, it is recommended to always use ANSI-92 style joins, where all joins are made explicit by 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>
By adopting consistent join syntax, you can avoid ambiguity and prevent similar errors in future queries.
The above is the detailed content of Why am I getting an 'Unknown column 'p.id' in 'on clause'' error in my MySQL query?. For more information, please follow other related articles on the PHP Chinese website!