oracle資料庫:欄位內資料(value1,value2,value3)的拆分合並
阿新 • • 發佈:2019-02-18
select * from TEST0531
1、將女生愛好合併為一行
select '女',wm_concat(hobby) hobby from TEST0531 where sex= '女'
wm_concat(列名),該函式可以把列值以","號分隔起來,並顯示成一行
2、將愛好拆分顯示(注意:資料庫中欄位內資料應以英文逗號隔開:value1,value,value3)
select distinct (name), regexp_substr(hobby, '[^,]+', 1, level) hobby from TEST0531 connect by regexp_substr(hobby, '[^,]+', 1, level) is not null
注意:distinct (name):使查詢資料根據name唯一,這樣查詢出的資料不會重複
注意:regexp_substr(hobby, '[^,]+', 1, level:運用了正則表示式(具體意思沒搞明白),
且這句話應與 connect by regexp_substr(hobby, '[^,]+', 1, level) is not null一同出現。
3、獲取與周有相同愛好的人
select distinct (name) from (select distinct (name), regexp_substr(hobby, '[^,]+', 1, level) hobby from TEST0531 connect by regexp_substr(hobby, '[^,]+', 1, level) is not null) h where instr( (select hobby from TEST0531 where name ='周'),h.hobby)>0
instr('abc','a');表示在abc中查詢有沒有a這個字元。>0表示字元存在
4、獲取與周有相同愛好的人的所有資訊
select * from TEST0531 where name in (select distinct (name) from (select distinct (name), regexp_substr(hobby, '[^,]+', 1, level) hobby from TEST0531 connect by regexp_substr(hobby, '[^,]+', 1, level) is not null) h where instr((select hobby from TEST0531 where name = '周'), h.hobby) > 0)