数据库中现有两张表,一张客户表(customer),一张订单表(order)
客户表数据大概3K多条,订单表数据有100W条左右
当需要查询客户的订单状态在退款,付款,部分付款,支付完成的客户时,出现了页面加载缓慢问题,大概需要6s左右才加载完成
表结构如下
--客户表--
CREATE TABLE `customer` (
`customer_id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '学员ID',
`customer_name` varchar(64) NOT NULL DEFAULT '' COMMENT '姓名',
`gender` tinyint(1) NOT NULL DEFAULT '0' COMMENT '性别,1为男,2为女',
`birthday` date DEFAULT NULL COMMENT '生日',
`email` varchar(30) NOT NULL DEFAULT '' COMMENT '邮箱',
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20374 DEFAULT CHARSET=utf8 COMMENT='后台学生信息表'
--订单表--
CREATE TABLE `erp_order` (
`order_id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`product_id` bigint(11) DEFAULT NULL COMMENT '产品ID',
`order_num` varchar(50) DEFAULT NULL COMMENT '订单编号',
`policy_id` bigint(11) DEFAULT NULL COMMENT '优惠政策',
`policy_amount` bigint(11) NOT NULL DEFAULT '0' COMMENT '优惠金额',
`sale_user_id` bigint(11) DEFAULT NULL COMMENT '销售顾问',
`customer_id` bigint(11) DEFAULT NULL COMMENT '学员ID',
`order_status` int(11) DEFAULT NULL COMMENT '订单状态 1 待客户激活 2 未支付 3 已部分支付 4 支付完成 5 已取消 6 退款中 7 已退款',
`order_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '下单时间',
PRIMARY KEY (`order_id`) USING BTREE,
KEY `index_order_time` (`order_time`) USING BTREE,
KEY `index_product_id` (`product_id`) USING BTREE,
KEY `index_order_num` (`order_num`) USING HASH,
KEY `index_order_service_status` (`service_status`) USING BTREE,
KEY `index_order_status` (`order_status`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=998096 DEFAULT CHARSET=utf8 COMMENT='订单信息表'
原查询sql 如下
SELECT
COUNT(0)
FROM
erp_customer ec
WHERE ec.`customer_id` IN
(SELECT DISTINCT
eo.`customer_id`
FROM
erp_order eo
WHERE eo.order_status IN (3, 4, 6, 7))
上述sql执行时长和explain如下
优化后的sql
SELECT
COUNT(0)
FROM
erp_customer ec
WHERE EXISTS
(SELECT DISTINCT
eo.`customer_id`
FROM
erp_order eo
WHERE eo.order_status IN (3, 4, 6, 7)
AND eo.`customer_id` = ec.`customer_id`)
优化后sql执行时长和explain如下
可见,执行时间从3.1s缩短到0.137s,提示很明显