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 表结构:
需求:拿到 cs_goods 表中最新的 100 个商品(按 created_at 倒序),且每个超市的商品不能超过 3
个(cs_merchant_id 是超市) 也就是一共需要拿到 100 个商品,但是每个超市不能超过 3 个。
在无法改变原有需求的前提下,又要考虑性能问题,
可以考虑降低数据基数,取最新的 1000 条数据来进行处理,
这样就比操作整张表的效率要高很多很多,压力也比较小
以下是正确的 sql,执行时间 0.111s
执行结果图: