oracle 一个字段存多个ID(或其他字段值)(以逗号","分割),并用该字段与其他表的ID(或其他字段值)关联查询,结果也放入一个字段中方法

tableA 的 authors_user字段里存多个ID(以逗号","分割),且关联 tableB的ID

有两种方法

一 运用WM_CONCAT()

SQL如下:

select A.ID,
       A.CODE,
      (select WM_CONCAT(B.NAME)
       from tableB B
       where instr(A.authors_user,B.ID) > 0)  as authors_user_name
from tableA A

其中,WM_CONCAT(B.NAME)拼接查询结果,instr(A.authors_user,B.ID) >0 匹配符合结果的数据

二 运用LISTAGG( , ) within group(order by )
select A.ID,
       A.CODE,
      (select listagg(B.NAME,',')
       within group(order by B.NAME)
       from tableB B
       where instr(A.authors_user,B.ID) > 0)  as authors_user_name
from tableA A

参考文章
oracle 一个字段存多个ID(或其他字段值)(以逗号","分割),并用该字段与其他表的ID(或其他字段值)关联查询方法

更多推荐