我遇到了mysql where
子句的一个小问题。
这是查询:
SELECT u.id user
, p.id product_purchased
, p.name product_name
, pl.store_id store
, COUNT(*) occurrences
, total_spent
, total_product_purchased
, pl.registration
FROM purchases_log pl
JOIN user u
ON pl.user_id = u.id
JOIN product p
ON pl.product_id = p.id
JOIN
( SELECT user_id
, SUM(price) total_spent
, COUNT(product_id) total_product_purchased
FROM purchases_log pl
GROUP
BY user_id
) t1
ON u.id = t1.user_id
WHERE pl.store_id IN (1,2,3)
AND occurrences > 1
GROUP
BY user
, product_name
ORDER
BY u.id ASC
, pl.registration ASC;
这是输出错误:
错误代码:1054 。 'where子句'0.067秒
中的未知列'出现'我已经尝试将AS
分配给事件或使用pl。
那么,有人可以解释我如何在where子句中正确定义count函数的结果吗?
答案 0 :(得分:2)
您需要使用HAVING
代替COUNT
,因为group by应用于WHERE
子句之后,因此,它不会知道任何组/聚合列,例如/:< / p>
SELECT u.id user,p.id product_purchased, p.name product_name, pl.store_id store, COUNT(*) AS occurrences, total_spent, total_product_purchased, pl.registration
FROM purchases_log pl
JOIN user u ON pl.user_id=u.id
JOIN product p ON pl.product_id=p.id
JOIN (SELECT user_id, SUM(price) AS total_spent,COUNT(product_id) AS total_product_purchased FROM purchases_log pl GROUP BY user_id) t1 ON u.id=t1.user_id
WHERE pl.store_id IN (1,2,3)
GROUP BY user, product_name
HAVING COUNT(*) > 1
ORDER BY u.id ASC, pl.registration ASC;
<强>更新强>
GROUP BY
中添加所有非聚合列,以获取用户和产品的所有组合。当前查询不会返回所有组合。EXPLAIN
并查看使用了哪些索引以及是否需要创建任何新索引。