Select 具有最近修改日期的行

Select the row with the most recent modified date

我有这个table:

user_id name email modified_date
1 John a@gmail.com 2022-01-01
1 John b@gmail.com 2022-01-02
1 Lucy c@gmail.com 2022-01-03
2 Joey d@gmail.com 2021-12-24
3 Mike e@gmail.com 2022-01-01
3 Mary f@gmail.com 2022-01-02

我正在尝试使用最近的 modified_date 获取唯一的 user_id 电子邮件。这是我的预期输出:

user_id email name
1 c@gmail.com Lucy
2 d@gmail.com Joey
3 f@gmail.com Mary

我用了limit 1,但是输出好像是随机的

有人可以帮我解决这个问题吗?

目前,您的查询可能类似于:

SELECT user_id, email
FROM email_addresses
GROUP BY user_id

你需要做一些不同的事情

SELECT email_addresses.*
FROM email_addresses
LEFT OUTER JOIN email_addresses AS b
    ON email_addresses.user_id = b.user_id
    AND b.modified_date > email_addresses.modified_date
WHERE b.user_id IS NULL

这通过与较新的记录配对(如果存在)来实现,然后 where 子句要求配对不成功。

你可以使用 row_number() 分区

架构 (PostgreSQL v10.0)

create table users(user_id integer, name varchar(10),   email varchar(20),  modified_date timestamp);

insert into users 
values
(1  ,'John',    'a@gmail.com',  '2022-01-01'),
(1  ,'John',    'b@gamil.com',  '2022-02-01');

查询#1

select user_id, email, name
from
(
SELECT user_id, name, email,row_number() over(partition by user_id order by modified_Date desc) as rnk
FROM users
  ) as t
  where rnk = 1;
user_id email name
1 b@gamil.com John

View on DB Fiddle