如何有效地从相关表中选择最新记录

时间:2019-03-16 11:55:24

标签: sql postgresql

这是我的工作,虽然有效,但速度很慢。我需要对其进行优化。

SELECT main_table.id
FROM main_table
INNER JOIN linked_table latest_linked_record ON latest_linked_record.id = (
       SELECT clever_alias.id
       FROM linked_table clever_alias
       WHERE clever_alias.claim_order_id = main_table.id
       ORDER BY clever_alias.updated_at DESC,
                clever_alias.id DESC
       LIMIT 1
)
WHERE latest_linked_record.some_column NOT IN (1, 19)

似乎我一生都在与之抗争,与MySQL,MSSQL,Oracle和Postgres一样。除了物化视图之类的策略之外,我还能做些什么来改善性能?

1 个答案:

答案 0 :(得分:0)

在Postgres中,我建议使用DISTINCT ON

SELECT mt.id
FROM main_table mt INNER JOIN
     (SELECT DISTINCT ON (lt.claim_order_id) lt.*
      FROM linked_table lt
      ORDER BY lt.claim_order_id, lt.claim_order_id DESC, lt.id DESC
     ) lt
     ON lt.claim_order_id = mt.id
WHERE lt.some_column NOT IN (1, 19);

当然,对于此查询,JOIN不是必需的:

SELECT lt.claim_order_id
FROM (SELECT DISTINCT ON (lt.claim_order_id) lt.*
      FROM linked_table lt
      ORDER BY lt.claim_order_id, lt.claim_order_id DESC, lt.id DESC
     ) lt
WHERE lt.some_column NOT IN (1, 19);