數據庫中現有兩張表,一張客戶表(customer),一張訂單表(order)sql
客戶表數據大概3K多條,訂單表數據有100W條左右數據庫
當須要查詢客戶的訂單狀態在退款,付款,部分付款,支付完成的客戶時,出現了頁面加載緩慢問題,大概須要6s左右才加載完成優化
表結構以下code
--客戶表-- 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 以下blog
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以下產品
優化後的sqlclass
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以下email
可見,執行時間從3.1s縮短到0.137s,提示很明顯後臺