(ORACLE)ROWNUM方式与MAX方式在获取最新数据时的效率比较
下午检查一段SQL时,发现获取最新数据时,可以采用两种方式的SQL写法:1、取记录后按日期逆序后取ROWNUM=1,2、对表的日期取MAX,再和原表关联,取出最大日期对应的数据。为了验证效率,做了以下实验。
数据量:
SELECT COUNT(*)
FROM GPRXSJB
WHERE GPDM = '000001'
AND FSRQ < TO_DATE('2007-9-11','YYYY-MM-DD')
结果为 4054行
SQL1(ROWNUM方式):
SELECT *
FROM
(
SELECT SPJ
FROM GPRXSJB
WHERE GPDM = '000001'
AND FSRQ < TO_DATE('2007-9-11','YYYY-MM-DD')
ORDER BY FSRQ DESC
)
WHERE
ROWNUM = 1;
执行平均时间为:7.8 s
SQL2(MAX方式):
SELECT *
FROM GPRXSJB A,
(
SELECT MAX(FSRQ) AS MAXDATE
FROM GPRXSJB
WHERE GPDM = '000001'
AND FSRQ < TO_DATE('2007-9-11','YYYY-MM-DD')
) B
WHERE A.GPDM = '000001'
AND A.FSRQ = B.MAXDATE
执行平均时间为:16 s
效率比较明细第一种要快得多。
可能原因分析:
按第二种方式,与原表关联的笛卡尔积维度较大,所以执行缓慢。
愿牛人们帮忙分析一下,谢谢。
数据量:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
SQL1(ROWNUM方式):
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
SQL2(MAX方式):
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
效率比较明细第一种要快得多。
可能原因分析:
按第二种方式,与原表关联的笛卡尔积维度较大,所以执行缓慢。
愿牛人们帮忙分析一下,谢谢。