首页 > 代码库 > SQL分页优化
SQL分页优化
1. 第一种(不可用,与不使用TOP没什么区别)【耗时15~20s】
SELECT * FROM
(
SELECT TOP 20 ROW_NUMBER() OVER(ORDER BY Id) AS Num, * FROM
(
SELECT * FROM Goods_1 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_2 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_3 WHERE Name Like ‘%测试%%‘ UNION ALL
SELECT * FROM Goods_4 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_5 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_6 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_7 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT * FROM Goods_8 WHERE Name Like ‘%测试%‘
) AS T
) AS T
WHERE Num BETWEEN ((2 - 1) * 10 + 1) AND 2 * 10;
2. 第二种(可用,耗时明显降低很多)【耗时2~4s】
SELECT * FROM
(
SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Num, * FROM
(
SELECT TOP 20 * FROM Goods_1 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_2 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_3 WHERE Name Like ‘%测试%%‘ UNION ALL
SELECT TOP 20 * FROM Goods_4 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_5 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_6 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_7 WHERE Name Like ‘%测试%‘ UNION ALL
SELECT TOP 20 * FROM Goods_8 WHERE Name Like ‘%测试%‘
) AS T
) AS T
WHERE Num BETWEEN ((2 - 1) * 10 + 1) AND 2 * 10;
这里的2指的是分页的页码,20指的是分页大小,这样的写法能降低耗时也可想而知了~
SQL分页优化