1. 使用正確的索引
- 索引通過減少掃描的數(shù)據(jù)量來加速數(shù)據(jù)檢索
select * from employees where last_name = 'smith';
-
如果多次查詢表的某一列,則為該列創(chuàng)建索引
-
如果您或您的應用根據(jù)條件需要來自多個列的數(shù)據(jù),則創(chuàng)建復合索引
2.避免選擇*
- 僅選擇那些需要的列,如果您選擇所有不需要的列,這只會消耗更多的服務器內(nèi)存并導致服務器在高負載或頻率時間下變慢
例如,您的表包含諸如created_at和updated_at以及時間戳之類的列,然后避免選擇*,因為它們在正常情況下不需要
低效查詢
select * from orders where order_date > '2023-01-01';
優(yōu)化查詢
select order_id, customer_id from orders where order_date > '2023-01-01';
- 優(yōu)化連接
- 確保 join 條件中使用的列上存在索引。
如果您使用主鍵連接表,則無需創(chuàng)建,因為主鍵已經(jīng)是索引
select orders.order_id, customers.name from orders join customers on orders.customer_id = customers.id where customers.country = 'usa';
在上面的查詢中,orders.customer_id 需要被索引,并且它與另一個表的關系
customers.id是customers表的主鍵,所以不需要創(chuàng)建索引
customers.country 需要被索引,因為它是一個條件
5.避免子查詢;使用連接代替
6.使用查詢緩存
- 如果您的查詢結果不經(jīng)常更改,請使用 mysql 的查詢緩存。
例如用戶和訂單列表以及其他不經(jīng)常更改的內(nèi)容
7. 對大表進行分區(qū)
CREATE TABLE orders ( order_id INT NOT NULL, order_date DATE NOT NULL, ... PRIMARY KEY (order_id, order_date) ) PARTITION BY RANGE (YEAR(order_date)) ( PARTITION p0 VALUES LESS THAN (2000), PARTITION p1 VALUES LESS THAN (2010), PARTITION p2 VALUES LESS THAN (2020), PARTITION p3 VALUES LESS THAN MAXVALUE );