update更新表数据或修改表数据

update对表数据进行更新

语法:update 表名 set 字段1=值1,字段2=值2 ... where 条件

注:若没有加where条件,将更新整个字段列很危险的操作,需确认!!!

当然update中值也是个select查询的结果

语法:update 表名 set 字段1=(select ...),字段2=值2 ... where 条件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
--查询原表
SQL> select * from emp3;
EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 1001 f2         bbb        1000 2024/4/1      1400.00               20
 1000 ff         bbb         123 2024/2/2     10000.00               20
 1002 f3                                       4000.00           

--更新一列的值,没有更where条件,可以看到job字段整个列都被修改,很危险的操作。
SQL> update emp3 set job='test' ;
3 rows updated
--打印结果
SQL> select * from emp3;
EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 1001 f2         test       1000 2024/4/1      1400.00               20
 1000 ff         test        123 2024/2/2     10000.00               20
 1002 f3         test                          4000.00           




--加where条件,仅修改符合where条件的行
SQL> update emp3 set job='aaa',sal=2000 where ename='ff';
1 row updated

SQL> commit;
Commit complete

SQL> select * from emp3;
EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 1001 f2         test       1000 2024/4/1      1400.00               20
 1000 ff         aaa         123 2024/2/2      2000.00               20
 1002 f3         test                          4000.00           


 --加where条件,仅修改符合where条件的行,将原来的job是test的行改为test2
 SQL> update emp3 set job='test2' where job='test';
2 rows updated

SQL> select * from emp3;
EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 1001 f2         test2      1000 2024/4/1      1400.00               20
 1000 ff         aaa         123 2024/2/2      2000.00               20
 1002 f3         test2                         4000.00     




 --嵌套select查询,将f3的sal和f2的sal相同
 --先查询f2的sal
 SQL> select sal from emp3 where ename='f2';
      SAL
---------
  1400.00

--更新sal,where ename='f3'
SQL>  update emp3 set sal=(select sal from emp3 where ename='f2') ,mgr=1000 where ename='f3';
1 row updated

SQL> select * from emp3;
EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 1001 f2         test2      1000 2024/4/1      1400.00               20
 1000 ff         aaa         123 2024/2/2      2000.00               20
 1002 f3         test2      1000               1400.00