小工具知识网

当前位置: 首页 > 行业知识 > sql Left Join 关联多条数据情况下只取一条数据

行业知识

sql Left Join 关联多条数据情况下只取一条数据

2026-11-12 08:47:09 来源:互联网转载

存在b表中foreign_key多条关联a表中的id

select a.name, b.agefrom table aleft join table b on a.id =b.foreign_key

需要只取b表中的一条数据(例如取最新的时间的一条)

1.解决方式:使用ROW_NUMBER () over()新增一列编号,排序后对新增列进行筛选

select a.name, b.age,ROW_NUMBER () OVER ( PARTITION BY b.id ORDER BY b.last_update_date DESC) AS group_idxfrom table aleft join table b on a.id =b.foreign_keywhere group_idx = 1 //新增列进行筛选(关联b表后为空的情况可加上:or group_idx is null)

2.解决方式:使用listagg函数多列转一行,再结合substr函数截取最后一条

select a.name, b.age,SUBSTR(listagg(b.id,'/') WITHIN GROUP (ORDER BY b.last_update_date DESC),-5) //固定数值数from table aleft join table b on a.id =b.foreign_key

上一篇:抽奖机服务器怎么用?

下一篇:双电源服务器功耗怎么算?