2016-03-02 99 views
1

我試圖用WHERE條件在MySQL PHPPDOSELECT AS,我得到了錯誤PHP MySQL選擇與WHERE列未找到?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total_consumers' in 'where clause'null 

我的查詢:

SELECT category.* , SUM(Consumer.capacity) AS total_consumers 
FROM company AS company 
RIGHT JOIN company AS Consumer ON (Consumer.category_id = company.category_id AND Consumer.company_type = 'Consumer' ) 
RIGHT JOIN category AS category ON (category.category_id = company.category_id ) 
WHERE total_consumers > 0 
GROUP BY category.category_title 

目標:

我想所有記錄Inc分類表,它們應該作爲消費者和生產者存在於公司表中,如果消費者null不選擇它

這裏是上面的查詢

的JSON結果如果我刪除WHERE條件我得到了以下JSON響應

http://json.live/166EaR

就像你看到的一些記錄有total_consumers : null不應該選擇

任何想法如何做我的觀點:(爲什麼我不能在WHERE語句中使用SELECT AS)

WHERE total_consumers > 
or 
WHERE total_consumers != null 
or 

WHERE xx NOT NULL 

回答

4

您不能在where子句中使用來自select的別名。您必須使用having子句:

SELECT category.* , SUM(Consumer.capacity) AS total_consumers 
FROM company AS company 
RIGHT JOIN company AS Consumer ON (Consumer.category_id = company.category_id AND Consumer.company_type = 'Consumer' ) 
RIGHT JOIN category AS category ON (category.category_id = company.category_id ) 
GROUP BY category.category_title 
having total_consumers > 0 
+1

只是爲了澄清 - 您可以使用別名,但不能使用聚合列。 WHERE限制考慮進行聚合的行,而HAVING子句在聚合發生後應用。 – MatsLindh

+0

我做了上面的事,我第一個錯誤'SQLSTATE [42000]:語法錯誤或訪問衝突:1064您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以在第6null行'GROUP BY category.category_title'附近使用正確的語法,並檢查第二個錯誤:SQLSTATE [HY000]:常規錯誤:1111組函數無效' – Jack

+0

@NinjaDevelopers請參閱我的更新回答 – Jens