尝试优化特定的 SQL 查询
Try optimize a specific SQL query
我使用这个 SQL 查询 (PostgreSQL) :
select *
from (select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties)
as toto
where toto.row_number=(select row_number
from (select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties)
as titi
where titi.oid1='4'
AND titi.oid2='1'
AND titi.oid3='')+1;
但它两次使用相同的 select :
select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties
是否可以将我的请求因式分解一次 select?
谢谢,
纪尧姆
select *
from (select lag ((oid1,oid2,oid3)) over (order by oid1, oid2, oid3) = ('4','1','') as is_requested_row
,s.*
from snmpProperties as s
) as s
where is_requested_row
;
加法,只是为了演示在row_number
的基础上也可以做到
select *
from (select min (case when (oid1,oid2,oid3) = ('4','1','') then rn end) over () base_rn
,s.*
from (select row_number() over (order by oid1, oid2, oid3) as rn, s.*
from snmpProperties as s
) as s
) as s
where rn = base_rn + 1
;
解释
1)
使用 LAG window 函数,每条记录查看其前一条记录的 (oid1,oid2,oid3) 向量(当排序为 oid1,oid2,oid3 时)并将其与('4','1','')。
当比较为真时,说明我们站在请求的记录上,记录后面有oid1='4', oid2='1' and oid3=''.
的记录
2)
使用 row_number window 函数,我们将行号赋予按 oid1、oid2、oid3 排序的记录。
使用 min window 函数,我们将 oid1、oid2 和 oid3 值为 '4'、'1' 和 ' 的行的 row_number ' 在集合中的每一行中。
我们取其 row_number 等于 row_number + 1
的行
我使用这个 SQL 查询 (PostgreSQL) :
select *
from (select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties)
as toto
where toto.row_number=(select row_number
from (select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties)
as titi
where titi.oid1='4'
AND titi.oid2='1'
AND titi.oid3='')+1;
但它两次使用相同的 select :
select row_number()
over (order by oid1, oid2, oid3)
as row_number, *
from snmpProperties
是否可以将我的请求因式分解一次 select?
谢谢, 纪尧姆
select *
from (select lag ((oid1,oid2,oid3)) over (order by oid1, oid2, oid3) = ('4','1','') as is_requested_row
,s.*
from snmpProperties as s
) as s
where is_requested_row
;
加法,只是为了演示在row_number
的基础上也可以做到select *
from (select min (case when (oid1,oid2,oid3) = ('4','1','') then rn end) over () base_rn
,s.*
from (select row_number() over (order by oid1, oid2, oid3) as rn, s.*
from snmpProperties as s
) as s
) as s
where rn = base_rn + 1
;
解释
1) 使用 LAG window 函数,每条记录查看其前一条记录的 (oid1,oid2,oid3) 向量(当排序为 oid1,oid2,oid3 时)并将其与('4','1','')。 当比较为真时,说明我们站在请求的记录上,记录后面有oid1='4', oid2='1' and oid3=''.
的记录2) 使用 row_number window 函数,我们将行号赋予按 oid1、oid2、oid3 排序的记录。 使用 min window 函数,我们将 oid1、oid2 和 oid3 值为 '4'、'1' 和 ' 的行的 row_number ' 在集合中的每一行中。 我们取其 row_number 等于 row_number + 1
的行