2013-10-02 67 views

回答

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

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

正如上面可以使用具有,或者您也可以加入針對其避免相關子查詢

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中

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的答案可能是解決此問題的更好方法。

相關問題