1 WITH Results AS ( 2 SELECT *,ROW_NUMBER () OVER (ORDER BY a.CreateDate DESC) RowIndex 3 FROM ( 4 (SELECT * FROM Remark_User_1 WITH (NOLOCK)) 5 UNION ALL 6 (SELECT * FROM Remark_SYSLog_1 WITH (NOLOCK)) 7 UNION ALL 8 (SELECT * FROM Remark_SYSLog_2 WITH (NOLOCK)) 9 UNION ALL 10 (SELECT * FROM Remark_User_2 WITH (NOLOCK)) 11 UNION ALL 12 (SELECT * FROM Remark_SYSLog_3 WITH (NOLOCK)) 13 UNION ALL 14 (SELECT * FROM Remark_User_3 WITH (NOLOCK)) 15 UNION ALL 16 (SELECT * FROM Remark_SYSLog_0 WITH (NOLOCK)) 17 UNION ALL 18 (SELECT * FROM Remark_User_0 WITH (NOLOCK)) 19 ) AS a 20 ), 21 ResultsCount AS ( 22 SELECT isnull(MAX(RowIndex), 0) ResultCount FROM Results 23 ) 24 SELECT a.*, ResultsCount.ResultCount,rd.Name AS TypeName 25 FROM Results a 26 LEFT JOIN ResultsCount ON 1 = 1 27 LEFT JOIN RemarkDataDictionary rd ON rd.ID = a.Type 28 WHERE RowIndex BETWEEN 1 AND 20
优化点:
1、避免使用*
2、主键、order by 后面的字段添加索引
3、封装为存储过程,消除sql编译的时间
4、先where后row_number