MySQL unknown column in ON clause
I have the following MySQL query:
And I’m getting this error:
As far as I can see the query looks right, any idea what could be wrong?
3 Answers 3
Don’t mix ANSI-89 style and ANSI-92 style joins. They have different precedence which can lead to confusing errors, and that is what has happened here. Your query is being interpreted as follows:
In the above, the joins using the JOIN keyword are evaluated first before the comma-style join is even considered. At that point the table p isn’t yet declared.
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.
I’d recommend always using ANSI-92 style joins, i.e. using the JOIN keyword:
As stated before there is a precedence issue using joins via the comma operator where the LEFT JOIN will be executed and so references to table aliases won’t exist at that time. Though you can implicitly tell MySQL to use a JOIN via that statement you may also tell MySQL to evaluate the comma joined tables first, then execute left join thusly:
Notice the comma separated tables are contained within parenthesis (). The table aliases and columns will now be available to your other JOINs.
I bumped into this error unknown column, the diff is the query is built thru HQL inside session.executeQuery(«select id, name, sum(paid), custType from cust group by brand») that’s why having to manually type inner join or join keyword is not an option as the hql is the one generating it. it produces a query sumthing like this:
it says «unknown c.custTypeId» column when I am 101% sure it bears that column.
the problem lies in the comma in «from customer, custType» line. it should be with the word JOIN as the answer stated above. but since it is HQL and is being generated, I can’t do that. What I did is modified by query and instead of typing select custType, I typed select custType.id, custType.code
I know it’s basic but for first timers like me, it was a struggle.
