只要我避免WHERE stream_json ...
可以修复它还是需要加入,它就可以工作?
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
只要我避免WHERE stream_json ...
可以修复它还是需要加入,它就可以工作?
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
您可以使用子句HAVING
访问他们无法接受的自定义别名WHERE
SELECT (SELECT count(*) FROM inner_table
WHERE inner_table.movie_id = outer_table.id) AS stream_json
FROM outer_table HAVING stream_json != 0
您不能在 WHERE 条件中使用别名。但是,您可以在 HAVING 条件下使用它。另一种选择是重复整个子查询,但这看起来很难看。我建议使用 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
您无法访问同一级别的列别名。您需要将其包装到派生表中:
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;
但 Kickstart 的答案可能是解决这个问题的更好方法。
如上所述,您可以使用 HAVING,或者您可以加入一个避免相关子查询的子选择
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
请注意,您不需要检查 stream_json != 0 因为它隐含在 INNER JOIN 中