mysql的分頁查詢是開發人員作業經常會遇到的問題,這里稍寫幾種簡單優化方法,
#表結構 MySQL [test]> show create table house\G; *************************** 1. row *************************** Table: house Create Table: CREATE TABLE `house_backup` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) COLLATE utf8mb4_bin NOT NULL DEFAULT '', `address` varchar(500) COLLATE utf8mb4_bin DEFAULT '', `area` varchar(100) COLLATE utf8mb4_bin DEFAULT '', `aspect` varchar(10) COLLATE utf8mb4_bin DEFAULT '', `house_type` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '', `price` varchar(10) COLLATE utf8mb4_bin DEFAULT '', `add_time` int(11) unsigned DEFAULT '0', `test_column` varchar(12) COLLATE utf8mb4_bin NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2379248 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin 1 row in set (0.00 sec) ERROR: No query specified #總數 MySQL [test]> select count(1) from house; +----------+ | count(1) | +----------+ | 1456960 | +----------+ 1 row in set (0.45 sec) #初始位置查詢 MySQL [test]> select id,title from house_backup limit 10\G; #查詢的資料忽略 10 rows in set (0.00 sec) ERROR: No query specified #10w的偏移量查詢 MySQL [test]> select id,title from house limit 100000,10\G; #查詢的資料忽略 10 rows in set (0.03 sec) ERROR: No query specified #100w的偏移量查詢 MySQL [test]> select id,title from house limit 1000000,10\G; #查詢資料忽略 10 rows in set (0.37 sec) ERROR: No query specified #隨著偏移量增大,查詢越來越耗時
這里用100w偏移量分頁sql做優化
一. 使用 IN 關鍵字
#這里先查詢id,再用in關鍵字查詢,正常情況id是主鍵索引,效率很高,如果是其他欄位需要先創建索引(查詢id的sql不做列印) MySQL [test]> select id,title from house_backup where id in (1000001,1000002,10000003,1000004,1000005,1000006,1000007,1000008,1000009,1000020)\G; #查詢資料忽略
Empty set (0.00 sec) ERROR: No query specified
二. 使用 BETWEEN ... AND ...
MySQL [test]> select id,title from house_backup where id between 2172904 and 2172913; #查詢資料忽略 11 rows in set (0.00 sec)
上面兩種查詢均需要保證id是有序,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/196106.html
標籤:其他
上一篇:Redis事務
下一篇:mysql分組函式與查詢
