0

It works as long as I avoid the WHERE stream_json ... can this be fixed or does it require JOINS?

SELECT id, stuff,
    (SELECT count(*) 
     FROM inner_table
     WHERE inner_table.movie_id = outer_table.id) 
          AS stream_json
FROM outer_table 
WHERE stream_json != 0
OZZIE
  • 5,351
  • 5
  • 48
  • 56

4 Answers4

1

You can use HAVING to access the custom aliases they cannot be entertained using WHERE clause

SELECT (SELECT count(*) FROM inner_table
WHERE inner_table.movie_id = outer_table.id) AS stream_json
FROM outer_table HAVING stream_json != 0

See this for reference

Community
  • 1
  • 1
M Khalid Junaid
  • 62,293
  • 9
  • 87
  • 115
1

You cannot use aliases in WHERE conditions. However, you can use it in HAVING conditions. Another choice is to repeat whole subquery but that looks ugly. I recommend using HAVING.

SELECT (SELECT count(*) FROM inner_table
WHERE inner_table.movie_id = outer_table.id) AS stream_json
FROM outer_table HAVING stream_json != 0
Kuzgun
  • 4,512
  • 4
  • 33
  • 48
0

As above you can use HAVING, or you can join against a subselect which avoid the correlated subquery

SELECT outer_table.id, outer_table.stuff, stream_json
FROM outer_table 
INNER JOIN
(
    SELECT movie_id, count(*) AS stream_json
    FROM inner_table
    GROUP BY movie_id
) Sub1
ON Sub1.movie_id = outer_table.id

Note that you do not need the check for stream_json != 0 for this as it is implicit in the INNER JOIN

Kickstart
  • 21,251
  • 2
  • 19
  • 33
0

You can't access the column alias on the same level. You need to wrap that into a derived table:

select *
from (
  SELECT id, 
         stuff,
         (SELECT count(*) 
          FROM inner_table
          WHERE inner_table.movie_id = outer_table.id) AS stream_json
  FROM outer_table
) t  
WHERE stream_json <> 0;

But Kickstart's answer is probably the better solution to this problem.

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843