我有一个orders
表,其中包含一行中一个用户订单的一个项目。因此每个用户都可以出现在很多行上。每个订单行都有一个状态 - PENDING
,APPROVED
,依此类推。我想为每个用户计算每个状态的订单数量,即批准的订单数量,仍有待处理的订单数量等等。我提出了以下问题:
SELECT
u.email, u.id,
(SELECT count(status) FROM orders WHERE user_id = o.user_id AND status = 'PENDING') pending,
(SELECT count(status) FROM orders WHERE user_id = o.user_id AND status = 'APPROVED') approved,
(SELECT count(status) FROM orders WHERE user_id = o.user_id AND status = 'REJECTED') rejected,
(SELECT count(status) FROM orders WHERE user_id = o.user_id AND status = 'ERROR') error
FROM orders o INNER JOIN users u ON o.user_id = u.id
GROUP BY o.user_id, u.email
问题在于它很慢!我在orders
表中有大约5 000条记录,它可以分钟执行。请建议如何优化它。
答案 0 :(得分:1)
您可以使用条件聚合删除子查询:
SELECT
u.email, u.id,
COUNT(CASE WHEN status = 'PENDING' THEN 1 END) pending,
COUNT(CASE WHEN status = 'APPROVED' THEN 1 END) approved,
COUNT(CASE WHEN status = 'REJECTED' THEN 1 END) rejected,
COUNT(CASE WHEN status = 'ERROR' THEN 1 END) error
FROM orders o INNER JOIN users u ON o.user_id = u.id
GROUP BY o.user_id, u.email
答案 1 :(得分:0)
实际上并不确定你需要分组:
SELECT u.email, u.id,o.pending,o.approved,o.rejected,o.error
FROM users u INNER JOIN
(
SELECT
user_id,
COUNT(CASE WHEN status = 'PENDING' THEN 1 ELSE 0 END) pending,
COUNT(CASE WHEN status = 'APPROVED' THEN 1 ELSE 0 END) approved,
COUNT(CASE WHEN status = 'REJECTED' THEN 1 ELSE 0 END) rejected,
COUNT(CASE WHEN status = 'ERROR' THEN 1 ELSE 0 END) error
FROM orders
) o
ON u.id = o.user_id