MYSQL查询选择计数字段

时间:2015-11-23 08:50:16

标签: mysql select count

select *, count(*) as total
from customer_data
where category = 'Fashion'
group by customer_id
order by total desc

从这个查询结果我怎么能拿到总数> gt的字段? 5?

1 个答案:

答案 0 :(得分:1)

您需要HAVING条款。另请尽量不要选择不在GROUP BY子句中的非聚合列或列。

SELECT aa.*, _aa.total
FROM (
    SELECT customer_id, COUNT(*) AS total
    FROM customer_data
    WHERE category = 'Fashion'
    GROUP BY customer_id
    HAVING COUNT(*) > 5
) AS _aa
INNER JOIN customer_data AS aa
ON _aa.customer_id = aa.customer_id
ORDER BY _aa.total DESC

查看herehere