「按訂單」上創建一個包含順序(followed_id, created_at)
這兩個領域現在的指標,有多大,我們都在談論這裏的大?如果這將是數以百萬計的量級。如何對類似下面的一個..
創建上的鍵followed_id, created_at, id
索引(這可能取決於在選擇,地點和ORDER BY子句。我有場改變量身定製的這對您的問題)
SELECT relationships.*
FROM relationships
JOIN (SELECT id
FROM relationships
WHERE followed_id = 1
ORDER BY created_at
LIMIT 10 OFFSET 10) itable
ON relationships.id = itable.id
ORDER BY relationships.created_at
的解釋會產生這樣的:
+----+-------------+---------------+------+---------------+-------------+---------+------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------+------+---------------+-------------+---------+------+------+-----------------------------------------------------+
| 1 | PRIMARY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Impossible WHERE noticed after reading const tables |
| 2 | DERIVED | relationships | ref | sample_rel2 | sample_rel2 | 5 | | 1 | Using where; Using index |
+----+-------------+---------------+------+---------------+-------------+---------+------+------+-----------------------------------------------------+
如果你仔細檢查,包含訂單,限制子查詢和偏移的條款將在指數運行直接而不是表格最後加入表格來獲取10條記錄。
它有一個區別,當你的查詢撥打limit 10 offset 10000
。它將從表中檢索所有10000條記錄並獲取前10個。這個技巧應該將遍歷限制在索引處。
重要說明:我在MySQL中測試了這個。其他數據庫在行爲上可能有細微的差異,但無論如何,這個概念都很好。