1. 首页
  2. IT资讯

mysql优化-(a)-技巧篇-not in等3种类型的sql优化

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)

本文来自投稿,不代表程序员编程网立场,如若转载,请注明出处:http://www.cxybcw.com/203275.html

联系我们

13687733322

在线咨询:点击这里给我发消息

邮件:1877088071@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

QR code