gpt4 book ai didi

sql - 排除与 Postgres 中每个父记录关联的第一条记录

转载 作者:行者123 更新时间:2023-11-29 14:28:30 24 4
gpt4 key购买 nike

有 2 个表,usersjob_experiences

我想返回所有 job_experiences 的列表,除了与每个用户关联的第一个。

用户

id 
---
1
2
3

工作经验

id | start_date | user_id
--------------------------
1 | 201001 | 1
2 | 201201 | 1
3 | 201506 | 1
4 | 200901 | 2
5 | 201005 | 2

想要的结果

id | start_date | user_id
--------------------------
2 | 201201 | 1
3 | 201506 | 1
5 | 201005 | 2

当前查询

select 
*
from job_experiences
order by start_date asc
offset 1

但这不起作用,因为它需要将偏移量单独应用于每个用户。

最佳答案

您可以使用横向连接来做到这一点:

select je.*
from users u cross join lateral
(select je.*
from job_experiences je
where u.id = je.user_id
order by id
offset 1 -- all except the first
) je;

为了提高性能,建议在 job_experiences(user_id, id) 上建立索引。

关于sql - 排除与 Postgres 中每个父记录关联的第一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55108397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com