Question

Could anyone please explain to me, why this mysql query throws an "Unknown column 'n.Id' in 'on clause'" error? It really doesn't make any sense to me.

SELECT n.Id,
       n.Name,
       COUNT(*)-1 AS level,
       seo.URLName
FROM NestedSetsTable AS n,
     NestedSetsTable AS p
LEFT JOIN SEO__Table AS seo
ON seo.ElementId = n.Id
AND seo.ElementCat = 1
WHERE n.lft BETWEEN p.lft AND n.rgt
GROUP BY n.lft
ORDER BY n.lft

Basically, the NestedSetsTable has the columns Id, Name, lft, rgt and the seo table has an ElementId (which contains the id of the Categorie), ElementCat (which contains a int, 1 in this case for categories, 2 would be products for example), URLName (which contains the name for a clean url. example.com/Categories/myCleanName for example )

Thank you

edit: I solved this problem, but the reason i'm asking anyway is because I want to figure out why n.Id is unknown in the ON clause because it really makes no sense to me.

Was it helpful?

Solution

Your join syntax is incorrect. I'm not sure how you want to join your two references to NestedSetsTable, so for now I'm assuming it's an inner join on Id. Also, I don't remember off-hand how MySQL handles grouping but typically you'd need to group on all non-aggregate columns in your query, e.g. n.Id, n.Name, seo.URLName

SELECT n.Id,
       n.Name,
       COUNT(*)-1 AS level,
       seo.URLName
FROM NestedSetsTable AS n
CROSS JOIN NestedSetsTable AS p
LEFT JOIN SEO__Table AS seo
ON seo.ElementId = n.Id
AND seo.ElementCat = 1
WHERE n.lft BETWEEN p.lft AND n.rgt
GROUP BY n.lft
ORDER BY n.lft

OTHER TIPS

Move the criteria AND seo.ElementCat = 1 to the WHERE clause: ....

LEFT JOIN SEO__Table AS seo ON seo.ElementId = n.Id WHERE n.lft BETWEEN p.lft AND n.rgt AND seo.ElementCat = 1

...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top