优化数据库记录获取时间

optimizing database record fetching time

我有 2 种大数据库 tables:[产品] 和 [product_position],产品可能会改变位置,所以我使用函数 product_pos(product_id) 以获取所述产品的当前(意思是最后)位置。在我的 Apex 报告中,我需要通过此查询显示每个产品及其当前位置:

SELECT id, serial_n, product_name, product_pos(id) as position
FROM product

函数product_pos:

create or replace FUNCTION product_pos(id_p IN NUMBER) 
    RETURN VARCHAR
AS
    res varchar2(20);
BEGIN
    select new_pos into res from product_position v where v.product_id=id_p order by date_move desc fetch first 1 rows only;
    return res; 
END product_pos;

我现在遇到的问题是获取时间,在顶点报告页面中,每个 loading/refresh 需要将近 30 秒。 我考虑过在产品 table 中添加一列 [position] 并通过对 [product_position] 上的每个 insert/update/delete 使用触发器来更新它,但是当有人更改手动在 [product] table 中的位置。 现在有没有一种方法可以减少处理时间,或者可以通过使新的 [position] 列仅由触发器更改来继续执行触发器解决方案而不会出现错误?

一个函数可能会阻碍优化器。您可能会发现简单的查询效果更好。例如:

SELECT p.id, p.serial_n, p.product_name, pp.new_pos as position
FROM product p LEFT JOIN
     (SELECT pp.*,
             ROW_NUMBER() OVER (PARTITION BY pp.product_id ORDER BY pp.id DESC) as seqnum
      FROM product_position pp
     ) pp
     ON pp.product_id = p.id AND pp.seqnum = 1;

或横向连接:

SELECT p.id, p.serial_n, p.product_name, pp.new_pos as position
FROM product p LEFT JOIN LATERAL
     (SELECT pp.*
      FROM product_position pp
      WHERE pp.product_id = p.id 
      ORDER BY pp.id DESC
      FETCH FIRST 1 ROW ONLY
     ) pp
     ON 1=1;

无论如何,您需要 product_position(product_id, id, new_pos) 上的索引以提高性能。