sql—如何在oracle中合并两个表

oo7oh9g9  于 2021-07-29  发布在  Java
关注(0)|答案(4)|浏览(556)

我有一个employee表,它有employee id和employee nameMap

另一个表是team\u emp\u map,它有team和employeeMap

因此,根据team\u emp\uMap表,团队id为1111的团队拥有这些员工emp\u 1、emp\u 2和emp\u 4。我需要在团队emp图和员工表的帮助下输出如下。

我在谷歌上查了很多,但没有成功。

bcs8qyzn

bcs8qyzn1#

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

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 || ',%'

看他演示。
结果:

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

ukxgm1gy2#

好的,我明白了,你需要用正确的多对多关联来修复你的team\u emp\u map表。
在这种情况下,我想您可以使用regex(regexp\u substr)来拆分逗号分隔的列。看看这篇文章吧。

8ljdwjyq

8ljdwjyq3#

一种方法是使用regexp\u substr和connect level by拆分第二个表的数组中的内容。
我举个例子:

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
koaltpgm

koaltpgm4#

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

相关问题