Oracle中某个字段里的值为逗号隔开的多个值

表a: 

a_usr_id(字符串型,关联表b的usr_id) 

123,124,125 

表b: 

usr_id ,   usr_name, 

123        name1 

124        name2 

125        name3 

 

直接用用sql语句,不用存储过程如何取得这样的数据集合: 

name1,name2,name3 

 

解决方案: 

 

SQL> select * from test; 

A_URS_ID 

-------------------------------------------------- 

123,125 

123,124,125 

 

SQL> select * from test1; 

 

URS_ID     URS_NAME 

---------- -------------------- 

123        name1 

124        name2 

125        name3 

 

SQL> with split_data as ( 

         select key, rn, substr(str, instr(str, ',', 1, rn)+1, 

                                instr(str, ',', 1, rn+1) - instr(str, ',', 1, rn) - 1) str 

            from (select a_urs_id key, ','||a_urs_id||',' str from test) a, 

                (select rownum rn from dual connect by rownum < 10) b 

         where instr(str, ',', 1, rn+1) > 0 ) 

     select key, substr(max(sys_connect_by_path(urs_name, ',')), 2) a_name 

         from split_data a, test1 b 

         where a.str = b.urs_id 

 

       start with rn = 1 

      connect by key = prior key and rn-1 = prior rn 

      group by key; 

 

KEY                  A_NAME 

-------------------- ------------------------------------------------------------ 

123,124,125          name1,name2,name3 

123,125               name1,name3 

 

你可能感兴趣的:(sql)