Say you have two tables with columns:
- table1: id, data
- table2: id, t1_ref (which is a FK to table1), some_other_column
Now I can write something like (I know that this can be written differently, more efficient, etc, not looking for those):
SELECT t1.data,
(SELECT count(*)
FROM table2 t2
WHERE t2.t1_ref = t1.id) AS nested_result
FROM table1 t1;
My question is, where can I use 'nested_result' in the rest of the main query? Can I use it in the FROM (in another nested select for instance)? Or in the WHERE? Or in a GROUP BY? Or on a ORDER BY? Anywhere else?
For example MySQL doesn't seem to like:
SELECT t1.data,
(SELECT count(*)
FROM table2 t2
WHERE t2.t1_ref = t1.id) AS nested_result
FROM table1 t1
WHERE nested_result > 100;
but what are the general rules here?