Question

I am trying to write a query that joins another table, but in this case, I need to use the value from one of the columns in the left table in my subquery. In doing so, I receive an error stating that mySQL cannot find a column with such a name.

First, here is my query that references 2 tables (t1 and t2) (@category is a parameter that is subbed in from my program):

SELECT t1.incID, t1.name, t1.sortBy, SQ.person, SQ.pointsValue
FROM table1 t1
LEFT OUTER JOIN (
    SELECT incID, person, IF( t1.sortBy=0, max(points), min(points) ) pointsValue
    FROM table2
    GROUP BY incID
) SQ ON SQ.incID = t1.incID
WHERE t1.category=@category
ORDER BY t1.name ASC
LIMIT 0 , 30

Now, when I execute this query, here is the error that is returned: #1054 - Unknown column 't1.sortBy' in 'field list'

If I replace t1.sortBy=0 with 0=0, the query executes fine, so it looks like I just seem to be getting mixed up on how mySQL does its order of operations?

Could someone please clarify how mySQL does the order of operations on a query like this and how I could work around this issue?

Was it helpful?

Solution

You cannot reference outer tables in derived table. You need to move your IF logic outwards:

SELECT t1.incID, t1.name, t1.sortBy, SQ.person, 
       IF( t1.sortBy=0, maxPoints, minPoints) pointsValue
FROM table1 t1
LEFT OUTER JOIN (
    SELECT incID, person, max(points) maxPoints, min(points) minPoints
    FROM table2
    GROUP BY incID
) SQ ON SQ.incID = t1.incID
WHERE t1.category=@category
ORDER BY t1.name ASC
LIMIT 0 , 30
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top