In our school, when a student is good, they get given a virtual pound (or dollar) which is stored in a database.
This is my query:
SELECT s.chosen_name, s.chosen_surname, s.regId, s.admission_number,
(
SELECT SUM(a.pounds_amount)
FROM tbl_pounds_log a
WHERE a.student_id=l.student_id
) AS total_pounds,
(
SELECT SUM(b.pounds_amount)
FROM tbl_pounds_log b
WHERE b.student_id=l.student_id
AND b.staff_id=:staffId
AND b.action_timestamp>(UNIX_TIMESTAMP()-3600)
) AS available_pounds
FROM TBL_student s
LEFT JOIN tbl_pounds_log l
ON l.student_id=s.admission_number
WHERE ((s.chosen_name LIKE :termOne AND s.chosen_surname LIKE :termTwo)
OR (s.chosen_name LIKE :termThree AND s.chosen_surname LIKE :termFour))
AND (total_pounds>=:lowerPoundLimit
AND total_pounds<=:upperPoundLimit)
GROUP BY s.admission_number
ORDER BY s.chosen_surname ASC, s.chosen_name ASC
LIMIT 0,10
(I’m using PHP PDO to perform the query hence the :text placeholders).
I’m having a bit of an issue when it comes to the WHERE condition in the parent query.
Where it says:
... AND (total_pounds>=:lowerPoundLimit and total_pounds<=:upperPoundLimit)
The total_pounds field is a column result of a subquery, however when I run the query it keeps coming up with:
Unknown column 'total_pounds' in 'where clause'
Does anyone know a solution to this?
Thanks
Phil
The problem is that the alias names is not yet available when the
WHEREclause is evaluated. The problem should be solved by moving the subqueries from theSELECTclause intoJOINclauses like this:It is also seems possible to write the query without subqueries: