1.修改单表的记录★
语法:
update 表名
set 列=新值,列=新值, .. .
where 筛选条件;
student表
id | name | sex | age | subject | score | teacher_id |
1 | 张三 | 男 | 15 | 语文 | 80 | 1 |
2 | 李四 | 女 | 15 | 语文 | 85 | 1 |
3 | 王二 | 男 | 16 | 语文 | 65 | 2 |
4 | 张三 | 男 | 15 | 英语 | 86 | 3 |
5 | 李四 | 女 | 15 | 英语 | 77 | 3 |
6 | 王二 | 男 | 16 | 英语 | 56 | 4 |
7 | 张三 | 男 | 15 | 数学 | 98 | 5 |
8 | 李四 | 女 | 15 | 数学 | 76 | 6 |
9 | 王二 | 男 | 16 | 数学 | 54 | 6 |
teacher表
id | name | sex | age |
1 | 张行 | 男 | 45 |
2 | 柳青青 | 女 | 35 |
3 | 杨逍遥 | 男 | 27 |
4 | 胡月华 | 女 | 55 |
5 | 李丽 | 女 | 38 |
6 | 王志杰 | 男 | 41 |
①修改张三的语文成绩为79
update student
set score =79
where name='张三' and subject ='语文'
②修改张三的语文成绩为79且修改其语文教师id为2
update student
set score =79,teacher_id =2
where name='张三' and subject ='语文'
2.修改多表的记录
SQL92语法(SQL SERVER 不支持):
update 表1 别名,表2 别名
set 列=值, ...
where 连接条件
and 筛选条件;
案例:
修改张三的语文老师的年龄为50
update student st ,teacher te
set te.age = 50
where st.teacher_id = te.id
and st.name ='张三' and subject ='语文'
SQL99语法(SQL SERVER 不支持):
update 表1 别名
inner | left l right join 表2 别名
on 连接条件
set 列=值, ...
where 筛选条件;
修改张三的语文老师的年龄为50
update student st ,
inner join teacher te
on st.teacher_id = te.id
set te.age = 50
where st.name ='张三' and subject ='语文'
SQL SERVER要实现上述功能:
update teacher
set age = 50
where id = (select teacher_id from student where name ='张三' and subject ='语文')