根据另一个表

时间:2017-02-23 08:28:09

标签: sql oracle sql-update

我有2张桌子: EMP和TMP_EMP都是相同的。我正在使用Oracle。

EMP:

+----------+----------+
| ID       | ALLOWED  |
+----------+----------+
| 1-xx     |    0     |
| 2-xx     |    1     |
| 3-xx     |    0     |
| 4-xx     |    2     |
+----------+----------+

TMP_EMP:

+----------+----------+
| ID       | ALLOWED  |
+----------+----------+
| 1-xx     |    0     |
| 2-xx     |    0     |
| 4-xx     |    0     |
| 5-xx     |    0     |
+----------+----------+

我想要做的是更新TMP_EMP表中的ALLOWED字段,并在EMP中将其设置为ALLOWED的相同值 表,如果员工存在于两个表中。 简而言之,最终的TMP_EMP表应如下所示:

TMP_EMP:

+----------+----------+
| ID       | ALLOWED  |
+----------+----------+
| 1-xx     |    0     |
| 2-xx     |    1     |
| 4-xx     |    2     |
| 5-xx     |    0     |
+----------+----------+

我已按如下方式编写了我的sql更新:

update TMP_EMP
set ALLOWED = IC.ALLOWED
WHERE ID in (
SELECT IC.ID 
FROM TMP_EMP tmp, EMP IC 
where IC.ID LIKE decode(instr(tmp.ID,'-'),0,tmp.ID,substr(tmp.ID,0,instr(tmp.ID,'-')-1)) || '%');

但这不起作用。我真的很感激这里的任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

UPDATE TMP_EMP t1
SET ALLOWED = (SELECT ALLOWED
               FROM EMP t2
               WHERE t2.ID LIKE DECODE(INSTR(t1.ID, '-'), 0, t1.ID,
                                       SUBSTR(t1.ID, 0, INSTR(t1.ID, '-')-1)) || '%')
WHERE EXISTS (SELECT ALLOWED
               FROM EMP t2
               WHERE t2.ID LIKE DECODE(INSTR(t1.ID, '-'), 0, t1.ID,
                                       SUBSTR(t1.ID, 0, INSTR(t1.ID, '-')-1)) || '%')

答案 1 :(得分:0)

没有在oracle中尝试但我会用CTE来做这件事。

;with tmp as (
    SELECT IC.ID 
    FROM TMP_EMP tmp, EMP IC 
    where IC.ID LIKE decode(instr(tmp.ID,'-'),0,tmp.ID,substr(tmp.ID,0,instr(tmp.ID,'-')-1)) || '%');
)
update te
set te.ALLOWED = tmp.ALLOWED
from TMP_EMP te
inner join tmp on tmp.ID = te.ID