1. 使用正確的索引
- 索引通過減少掃描的數據量來加速數據檢索
select * from employees where last_name = 'smith';
-
如果多次查詢表的某一列,則為該列創建索引
-
如果您或您的應用根據條件需要來自多個列的數據,則創建復合索引
2.避免選擇*
- 僅選擇那些需要的列,如果您選擇所有不需要的列,這只會消耗更多的服務器內存并導致服務器在高負載或頻率時間下變慢
例如,您的表包含諸如created_at和updated_at以及時間戳之類的列,然后避免選擇*,因為它們在正常情況下不需要
低效查詢
select * from orders where order_date > '2023-01-01';
優化查詢
select order_id, customer_id from orders where order_date > '2023-01-01';
- 優化連接
- 確保 join 條件中使用的列上存在索引。
如果您使用主鍵連接表,則無需創建,因為主鍵已經是索引
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表的主鍵,所以不需要創建索引
customers.country 需要被索引,因為它是一個條件
5.避免子查詢;使用連接代替
6.使用查詢緩存
- 如果您的查詢結果不經常更改,請使用 mysql 的查詢緩存。
例如用戶和訂單列表以及其他不經常更改的內容
7. 對大表進行分區
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 );