您好,登錄后才能下訂單哦!
需求描述:兩張表,如下,需要查詢tmp1表中id_new在tmp2中的name
select from tmp1;
select from tmp2;
方法一:
好處:簡單,直接sql展示
劣處:如果主表數據量太大,十幾億的話,性能會大大下降,此時建議第二種方法
select a.id_old,
to_char(wm_concat(distinct a.id_new)) id_new,
to_char(wm_concat(distinct b.name)) name
from tmp2 b,
(select a.id_old, regexp_substr(a.id_new, '[^,]+', 1, level) id_new
from tmp1 a
connect by level <= regexp_count(a.id_new, ',') + 1) a
where a.id_new = b.id_old(+)
group by a.id_old;
方法二:創建自定義函數來實現
create or replace function f_tmp_split(p_str varchar2, p_f varchar2)
return varchar2 is
v_pos pls_integer := 0; --獲取當前分隔符位置
v_pre_pos pls_integer := 1; --從第幾位開始截取
v_len pls_integer := 0; --字符串長度
v_len1 pls_integer := 0; --分隔符長度
v_result dbms_sql.Varchar2_Table; --結果集
v_num pls_integer := 1; --元素數量
v_name_class varchar2(1000); --返回的集合
v_name_tmp varchar2(1000); --返回拼接的值
begin
v_len := length(p_str);
v_len1 := length(p_f);
while v_pos < v_len loop
v_pos := instr(p_str, p_f, v_pre_pos);
if v_pos = 0 then
v_pre_pos := v_len;
v_result(v_num) := substr(p_str, v_pre_pos);
begin
select a.name
into v_name_tmp
from tmp2 a
where a.id_old = v_result(v_num);
exception
when no_data_found then
v_name_tmp := '';
end;
v_name_class := v_name_class || v_name_tmp;
if v_pre_pos >= v_len then
exit;
end if;
else
v_result(v_num) := substr(p_str, v_pre_pos, v_pos - v_pre_pos);
begin
select a.name || p_f
into v_name_tmp
from tmp2 a
where a.id_old = v_result(v_num);
exception
when no_data_found then
v_name_tmp := '';
end;
v_name_class := v_name_class || v_name_tmp;
v_pre_pos := v_pos + v_len1;
end if;
end loop;
return v_name_class;
end;
效果如下:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。