我正在尝试在 MySQL 中使用条件WHERE
SELECT AS
PHP
PDO
,我收到错误
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
不能在 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