oracle中如何合并两个表

How to merge two tables in Oracle

我有一个员工 table,它有员工 ID 和员工姓名映射

另一个 table 是 TEAM_EMP_MAP,它有团队和员工映射

因此根据 TEAM_EMP_MAP table,团队 ID 为 1111 的团队拥有这些员工 EMP_1、EMP_2 和 EMP_4。 在 TEAM_EMP_MAP 和 EMPLOYEE table.

的帮助下,我需要如下所示的输出

我在 google 上检查了很多,但没有成功。

一种选择是在表连接的 ON 子句中使用运算符 LIKE,如下所示:

SELECT t.ORG_ID TEAM_ID, 
       e.EMP_NM EMPLOYEE_NAME 
FROM TEAM_EMP_MAP t INNER JOIN EMPLOYEE e
ON ',' || t.EMPLOYEES || ',' LIKE '%,' || e.EMP_ID || ',%'

见他demo
结果:

> TEAM_ID | EMPLOYEE_NAME
> :------ | :------------
> 1111    | EMP_1        
> 1111    | EMP_3        
> 1111    | EMP_4   

好的,我明白了,你需要用正确的多对多关联来修复你的 TEAM_EMP_MAP table。

我认为您可以在这种情况下使用 Regex (REGEXP_SUBSTR) 来拆分逗号分隔的列。 看看这个 post 让它工作。

一种方法是使用 REGEXP_SUBSTR 和 CONNECT LEVEL BY 来拆分第二个 table.

数组中的内容

举个例子:

SQL> create table y ( id_emp number , name varchar2(2) ) ;

Table created.

SQL> insert into y values ( 101 , 'A' ) ;

1 row created.

SQL> insert into y values ( 104, 'B' ) ;

1 row created.

SQL> insert into y values ( 103 , 'C' ) ;

1 row created.

SQL> commit ;

Commit complete.

SQL> select * from t ;

        ID VAL
---------- -------------
      1111 101,104,103

SQL> select * from y ;

    ID_EMP NAME
---------- ----
       101 A
       104 B
       103 C

SQL> with emps as ( SELECT regexp_substr(val, '[^,]+', 1, LEVEL) as empid FROM t
  2  CONNECT BY regexp_substr(val, '[^,]+', 1, LEVEL) IS NOT NULL )
  3  select y.name , emps.empid from y inner join emps on ( y.id_emp = emps.empid ) ;

NAME EMPID
---- -----------------------------
A    101
B    104
C    103
with t as (
select org_id
      ,employees txt
  from team_emp_map
 where org_id = 1111
)
,emp as ( -- split string into records
select org_id
      ,regexp_substr(t.txt, '\d+', 1, level) emp_id
  from t
connect by regexp_substr(t.txt, '\d+', 1, level) is not null
)
select emp.org_id
      ,employee.emp_nm
  from emp
      ,employee
 where emp.emp_id = employee.emp_id