该 sql 语句在生产环境执行需要 50s,如何改进它
SELECT
`a`.*
FROM
`cs_goods` AS `a`
WHERE
( SELECT COUNT(`b`.`id`) FROM `cs_goods` AS b WHERE `b`.`cs_merchant_id` = `a`.`cs_merchant_id` AND `b`.`created_at` > `a`.`created_at` AND `status` = 1 and `audit_status` = 2 and `sq_type` <> 3 ) < 3
AND `status` = 1 and `audit_status` = 2 and `sq_type` <> 3
ORDER BY
`a`.`created_at` DESC LIMIT 100;
cs_goods
表结构:
id | cs_merchant_id | goods_name | status | audit_status | sq_type | created_at | updated_at |
---|---|---|---|---|---|---|---|
1 | 10000 | 测试商品1 | 1 | 2 | 2 | 2019-08-01 19:35:06 | 2019-08-03 09:54:32 |
2 | 10000 | 测试商品2 | 1 | 2 | 2 | 2019-08-01 19:35:06 | 2019-08-03 09:54:32 |
需求:拿到 cs_goods
表中最新的 100 个商品(按 created_at
倒序),且每个超市的商品不能超过 3 个(cs_merchant_id
是超市)
也就是一共需要拿到 100 个商品,但是每个超市不能超过 3 个。
在无法改变原有需求的前提下,又要考虑性能问题,
可以考虑降低数据基数,取最新的 1000 条数据来进行处理,
这样就比操作整张表的效率要高很多很多,压力也比较小
以下是正确的
sql
,执行时间 0.111s执行结果图: