SQL - select 每个外键只有最新记录

SQL - select only latest record for each foreign key

你好所以我的问题基本上是,我有一个 table files 像这样:

foreign_key string created_at
1 "a" 2021-11-10
2 "b" 2021-11-15
2 "c" 2021-11-18

现在我需要的是 select 每个不同的 foreign_key 一个记录(字符串)并且它总是需要是 最新的 (created_at)

不能在select秒内使用子查询因为速度。

结果应如下所示:

foreign_key string created_at
1 "a" 2021-11-10
2 "c" 2021-11-18

使用ROW_NUMBER:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY foreign_key
                                   ORDER BY created_at DESC) rn
    FROM yourTable t
)

SELECT foreign_key, string, created_at
FROM cte
WHERE rn = 1;

另一种方法,使用连接:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT foreign_key, MAX(created_at) AS max_created_at
    FROM yourTable
    GROUP BY foreign_key
) t2
    ON t2.foreign_key = t1.foreign_key AND
       t2.max_created_at = t1.created_at;