SELECT cols,(SELECT内部查询)AS innercol FROM表WHERE innercol的东西

时间:2013-10-02 09:59:40

标签: mysql

只要我避免WHERE stream_json ...可以修复它还是需要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

4 个答案:

答案 0 :(得分:1)

您可以使用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

See this for reference

答案 1 :(得分:1)

您不能在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

答案 2 :(得分:0)

如上所述,你可以使用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中

答案 3 :(得分: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的回答可能是解决这个问题的更好方法。