表1
EID EMPLOYEE_NAME DESIGNATION REPORTING_MANAGER FLAG
1 TIM COOK CEO Null Null
2 MILLER CTO TIM COOK Null
3 BRAD COO TIM COOK Null
4 WILLIAM HRD TIM COOK Null
5 JOHN TECH MANAGER(DEV) WILLIAM Null
6 WALLACE TECH MANAGER(TEST) WILLIAM Null
7 SUNDAR SWIFT DEV JOHN Null
8 PETER SWIFT DEV JOHN Null
9 STEVE TEST ENGINEER WALLACE Null
表2
EID EMPLOYEE_NAME REPORTING_MANAGER_ID
我想生成类似下面的内容
EID EMPLOYEE_NAME REPORTING_MANAGER_ID
1 TIM COOK Null
2 MILLER 1
3 BRAD 1
4 WILLIAM 1
5 JOHN 4
6 WALLACE 4
7 SUNDAR 5
8 PETER 5
9 STEVE 6
我尝试了以下查询,它成功运行但不在table2中插入数据。
INSERT INTO table2 (
E_ID
,EMPLOYEE_NAME
,REPORTING_MANAGER_ID
)
SELECT e.E_ID
,e.EMPLOYEE_NAME
,rm.E_ID AS REPORTING_MANAGER_ID
FROM table1 e
LEFT JOIN table1 rm ON rm.EMPLOYEE_NAME = e.REPORTING_MANAGER
WHERE e.FLAG = NULL
有人帮助我
答案 0 :(得分:3)
INSERT INTO table2 (E_ID,EMPLOYEE_NAME,REPORTING_MANAGER_ID)
SELECT e.E_ID , e.EMPLOYEE_NAME, rm.E_ID
FROM table1 e
LEFT JOIN table1 rm ON rm.EMPLOYEE_NAME = e.REPORTING_MANAGER
WHERE e.FLAG is NULL
如果您将列与null
进行比较,则会返回null
,这将从您的select
语句中返回任何行。请改用is null
。
答案 1 :(得分:0)
下面提到的两个查询将给出您需要的结果。
- 使用SubQuery
INSERT INTO table2 ( EID ,员工姓名 ,REPORTING_MANAGER_ID ) SELECT t1.EID t1.Employee_Name, ( 选择EID FROM table1 t2 在哪里t1.EMPLOYEE_NAME = t2.REPORTING_MANAGER )AS REPORTING_MANAGER_ID FROM table1 t1
- 使用加入条件
INSERT INTO table2 ( EID ,员工姓名 ,REPORTING_MANAGER_ID ) SELECT t1.EID, t1.EMPLOYEE_NAME, t2.REPORTING_MANAGER FROM table1 t1 LEFT OUTER JOIN table1 t2 在t1.EMPLOYEE_NAME = t2.REPORTING_MANAGER