看起來使用order by + limit的確很慢,使用order by有點慢,而使用just limit是相當快的。這些查詢的解釋都使用filesort。類似的是'%search%'兩端狂放,所以我知道它不能使用索引。mysql order by + limit slows query down
我不明白爲什麼通過限制的訂單比僅僅通過訂單慢得多。
如果我有下面的查詢,大約需要250毫秒:(在同一格式中有多個類似的查詢)。這使用AND限制的順序。 (最慢)
$this->db->select('category');
$this->db->from('items');
$this->db->where('deleted',0);
$this->db->distinct();
$this->db->like('category', $search);
$this->db->order_by("category", "asc");
$this->db->limit($limit);
如果我有下面的查詢大約需要65毫秒毫秒(有多個相同的格式類似的查詢)。這僅使用LIMIT(最快)
$this->db->select('category');
$this->db->from('items');
$this->db->where('deleted',0);
$this->db->distinct();
$this->db->like('category', $search);
$this->db->limit($limit);
如果我有後續的查詢需要花費大約75ms毫秒(有相同的格式多個類似的查詢)
$this->db->select('category');
$this->db->from('items');
$this->db->where('deleted',0);
$this->db->distinct();
$this->db->like('category', $search);
$this->db->order_by("category", "asc");
'Order by'需要對整個結果集進行排序。這需要時間。 'limit'只是在SQL引擎遇到它們時返回行。 –
您可以嘗試添加索引覆蓋列(刪除,類別),或者只是索引覆蓋列類別。 – Juho
您可能希望爲「類別」列編制索引,以改進使用「按類別排序」的查詢。 –