This simple query:
select exam.id as exam_id,
(select count(*) from dataset where dataset.id = exam.id) as n_dataset
from exam
where n_dataset = 0
returns the following error:
ERROR 1054 (42S22) at line 1: Unknown column 'n_dataset' in 'where clause'
Why?
Best Answer
Because the order of operations with the
WHERE
clause is applied first before theSELECT
operator. Son_dataset
doesn't exist yet when theWHERE
clause is being applied.You would need to use
COUNT()
as a window function (version of MySQL depending, you should update your tags to include the version) to get the results you're looking for.Or you can create your
COUNT()
query in a CTE first, then re-join to your table later on.But interpreting your logic further, it sounds like your actual end goal is to get all
exams
that don't have any correlatingdatasets
. You can accomplish that a lot simpler with aLEFT JOIN
this way: