遇到這情況通常都是兩個原因
第一種情況好解,把慢的SQL語法都整理一下,使用索引就可以!
EX:
SELECT * FROM table1
WHERE order_time
BETWEEN 1600852500 AND 1601842200
這時候可以對order_time這欄位加一個index
CREATE INDEX order_time
ON `table1` (`order_time`);
這一句SQL的查詢速度會大大提升,本來要花10秒,現在可能不到1秒就跑出來。這是你加CPU & RAM也不會達到的效果!
那全部的欄位都加上索引不就世界和平嗎??
不~索引愈多insert要花的時間愈久,所以要取一個平衝點,把全部的SQL都整理起來,找出共同的條件,再建立索引,盡可能讓使用頻率高的語法都吃到索引。
BUT終有一天這語法還是有可能會慢,那就是資料太多了
把SQL列出來
table: tasks
SELECT * FROM `tasks` WHERE user_id = "102968676886378479010" AND parent_id in (1) AND status IN (1) ORDER BY created_timestamp ASC
SELECT * FROM `tasks` WHERE user_id = "102968676886378479010" AND parent_id = 0 AND status = 1 ORDER BY created_timestamp ASC
SELECT id, parent_id, name, created_timestamp FROM `tasks` WHERE user_id = "102968676886378479010" AND status IN (1) ORDER BY created_timestamp ASC
table: records
SELECT * FROM `records` WHERE user_id = "102968676886378479010" AND date = "2020-09-24"
SELECT date, SUM(spend_time) as spend_time FROM `records` WHERE user_id = "102968676886378479010" AND (date BETWEEN "2020-09-17" AND "2020-09-24") GROUP BY `date` ORDER BY date ASC
SELECT * FROM `records` WHERE user_id = "102968676886378479010" AND (date BETWEEN "2020-09-17" AND "2020-09-24")
來找共同的條件~
這兩個欄位出現的頻率最高
user_id & parent_id
直接來做一個複合式的索引
搜尋的欄位出現user_id、user_id AND parent_id,就可以吃到這索引
PS: user_id一定要排在前面
CREATE INDEX userid_parentid
ON `tasks` (`user_id`, `parent_id`);
user_id & date
一樣來做複合式的索引
CREATE INDEX userid_date
ON `records` (`user_id`, `date`);
今天先這樣謝謝大家~