oracle 如何在同一个表上使用最大子查询优化选择?

atmip9wb  于 2022-11-22  发布在  Oracle
关注(0)|答案(2)|浏览(159)

我们有很多这样的老选择:

SELECT
    tm."ID",tm."R_PERSONES",tm."R_DATASOURCE", ,tm."MATCHCODE",
    d.NAME   AS DATASOURCE,
    p.PDID
FROM TABLE_MAPPINGS tm,
     PERSONES p,
     DATASOURCES d,
     (select ID
      from TABLE_MAPPINGS
      where (R_PERSONES, MATCHCODE) 
            in (select 
                  R_PERSONES, MATCHCODE
                from TABLE_MAPPINGS
                where 
                    id in (select max(id) 
                           from TABLE_MAPPINGS 
                           group by MATCHCODE)
               )
     ) tm2                    
WHERE tm.R_PERSONES = p.ID
  AND tm.R_DATASOURCE=d.ID
  and tm2.id = tm.id;

这些表很大,查询需要很长时间,如何重建?
谢谢你

2mbi3lxu

2mbi3lxu1#

您只能使用以下语句查询表一次(未经测试,因为您没有提供创建表语句或示例数据的最小示例):

SELECT *
FROM   (
  SELECT m.*,
         COUNT(CASE WHEN rnk = 1 THEN 1 END)
           OVER (PARTITION BY r_persones, matchcode) AS has_max_id
  FROM   (
    SELECT tm.ID,
           tm.R_PERSONES,
           tm.R_DATASOURCE,
           tm.MATCHCODE,
           d.NAME AS DATASOURCE,
           p.PDID,
           RANK() OVER (PARTITION BY tm.matchcode ORDER BY tm.id DESC) As rnk
    FROM   TABLE_MAPPINGS tm
           INNER JOIN PERSONES p    ON tm.R_PERSONES = p.ID
           INNER JOIN DATASOURCES d ON tm.R_DATASOURCE = d.ID
  ) m
)
WHERE  has_max_id > 0;

首先使用RANK解析函数找到最大值ID,然后使用COUNT解析函数中的条件聚集找到所有相关的r_persones, matchcode对。

  • 注意:您希望使用RANKDENSE_RANK分析函数来匹配最大值,因为它可以在每个分区中匹配多行;而ROW_NUMBER只会将每个分区的一行放在第一位。*
368yc8dk

368yc8dk2#

您正在查询table_mappings 3次;只做一次怎么样?

WITH
   tab_map
   AS
      (SELECT a.id,
              a.r_persones,
              a.matchcode,
              a.datasource,
              ROW_NUMBER ()
                 OVER (PARTITION BY a.matchcode ORDER BY a.id DESC) rn
         FROM table_mappings a)
SELECT tm.id,
       tm.r_persones,
       tm.matchcode,
       d.name AS datasource,
       p.pdid
  FROM tab_map tm
       JOIN persones p ON p.id = tm.r_persones
       JOIN datasources d ON d.id = tm.r_datasource
 WHERE tm.rn = 1

相关问题