or子句需要较长的时间

8ftvxx2r  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(359)

下面有一个查询示例,但它将永远运行。。如果我做了联合,那么我必须复制整个大型查询。。有什么帮助吗

select columns 
 from table a
 join (select *
         from ( select *, row_number() over( partition BY id ORDER BY date ) row_seq
                  from table b
              ) where row_seq = 1
       ) o ON  a.id = o.id OR  a.id = o.src_id 
 left join table p  on a.partner_c = p.id
 left join table pp on a.parnt_id = pp.id
fiei3ece

fiei3ece1#

内部

select *
from ( 
    select *,
        row_number() over( partition BY id ORDER BY date ) row_seq
    from table b
) where row_seq = 1

可以使用以下限定子句编写:

select *,
from table b
qualify row_number() over( partition BY id ORDER BY date ) = 1

可以推进到cte中,如:

WITH raw_rows AS (
    select *,
    from table b
    qualify row_number() over( partition BY id ORDER BY date ) = 1
) 
select columns 
from table a
join raw_rows o ON (a.id = o.id OR  a.id = o.src_id)
left join table p  on a.partner_c = p.id
left join table pp on a.parnt_id = pp.id

也就是说你可以把整件事结合起来 table a 以及 raw_rows o ```
WITH raw_rows AS (
select *,
from table b
qualify row_number() over( partition BY id ORDER BY date ) = 1
), a_and_o AS (
select a.columns
,o.columns
from table a
join raw_rows o ON a.id = o.id

UNION ALL

select a.columns
    ,o.columns 
from table a
join raw_rows o ON a.id = o.src_id

)
select columns
from a_and_o a
left join table p on a.partner_c = p.id
left join table pp on a.parnt_id = pp.id

但这会给你一个稍微不同的结果,如果 `o.src_id == o.id` 对于任何一行,因为它将匹配这两个诗句或维辛将有这些行一次。您可以通过交换到union进行重复数据消除来按成本向组付费,但是如果您有许多要保留的行,那么这些行将丢失。或者你可以把工会的后半部分改为不包括那些与

join raw_rows o ON a.id = o.src_id AND o.src_id != o.id

取决于您的数据和需要。

相关问题