1. not in 和 <> 的优化-->left join

SELECT customer_id, first_name, last_name, email 
FROM customer
WHERE customer_id 
NOT IN (SELECT customer_id FROM payment);

--优化后
SELECT a.customer_id, a.first_name, a.last_name, a.email
FROM customer a
LEFT JOIN payment b ON a.customer_id=b.customer_id
WHERE b.customer_id IS NULL;

2. 大表的数据修改要分批处理

比如1000万行记录在表中要删除, 或者更新100万行记录;

优化方案: 一次只删除/删除5000条, 然后sleep几秒(暂停几秒)-->给主从同步缓冲时间;

3. 汇总查询的优化 select count(*)-> 增加汇总表

增加一个汇总表, 每天更新一次汇总值;

然后每次查询时, 汇总表+实时表(time>date(now()))即可;

SELECT COUNT(*) FROM product_comment WHERE product_id=999;

--增加汇总表 product_comment_cnt
CREATE TABLE product_comment_cnt(product_id INT, cnt INT);

--查询时:
SELECT SUM(cnt) FROM(
    SELECT cnt FROM product_comment_cnt WHERE product_id = 999
    UNION ALL
    SELECT count(*) FROM product_comment WHERE product_id = 999 AND timestr>DATE(now())
);

--
mysql> select DATE(now());
+-------------+
| DATE(now()) |
+-------------+
| 2020-09-12  |
+-------------+
1 row in set (0.01 sec)

丰木
322 声望19 粉丝

遇见超乎想象的自己!


引用和评论

0 条评论