php mysql SELECT AS与WHERE列未找到?

Jac*_*ack 1 php mysql

我试图使用WHEREMySQL的条件下PHP PDOSELECT AS,我得到了错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total_consumers' in 'where clause'null
Run Code Online (Sandbox Code Playgroud)

我的查询:

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
Run Code Online (Sandbox Code Playgroud)

目标:

我想获取所有记录的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
Run Code Online (Sandbox Code Playgroud)

Jen*_*ens 5

您不能selectwhere子句中使用别名.你必须使用这个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 
Run Code Online (Sandbox Code Playgroud)