我正在尝试根据购买的商品数量对所有客户进行“分类”,并显示每个分类的数量。我试图查看有多少人(account_id)购买了一件商品,有多少人购买了两件商品,一直到九件商品,然后是十件或更多。
这是我正在使用的查询 - 对于它的价值,我希望查询对销售进行全表扫描以生成结果,但整个过程需要永远!
我来自 Oracle 背景,我像在 Oracle 中一样编写查询。
select thecnt
, count(*)
from (select count(*)
, case when count(*) >= 10 then 'tenormore' else cast(count(*) as char) end thecnt
from sales
where created >= SUBDATE( CURRENT_DATE(), INTERVAL 60 DAY )
group by account_id) sub
group by thecnt
order by thecnt;
mysql 在处理子查询时有什么陷阱吗?
解释计划
+----+-------------+-------------------+-------+---------------+---------+---------+------+---------+----------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------------------+-------+---------------+---------+---------+------+---------+----------+-----------------------------------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 2143248 | 100.00 | Using temporary; Using filesort |
| 2 | DERIVED | sales | range | created | created | 8 | NULL | 2012492 | 100.00 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+-------------------+-------+---------------+---------+---------+------+---------+----------+-----------------------------------------------------------+
2 rows in set, 1 warning (1 hour 4 min 6.14 sec)
mysql> describe sales;
+-----------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+-------+
| account_id | char(36) | NO | PRI | NULL | |
| created | datetime | NO | MUL | NULL | |
| histogram_value | bigint(20) unsigned | NO | PRI | NULL | |
+-----------------+---------------------+------+-----+---------+-------+