SQL Update的四种常见写法
/*
实验对象:两个学生表
1. 一个stu学生表,一个stu1学生表.
2. 上述表有三个字段 (学生id,学生性别,学生名字)
*/
/*
update语句常见场景,分为两大类:
1.单表update
2.多表关联update
*/
-- 1.1 单表update单字段
update stu t set t.NAME = 'mike' where t.ID = '1';
-- 1.2 单表update多字段
update stu t set t.NAME = 'mike', t.SEX = '1' where t.ID = '2';
/*
多表关联update的时候,记得要加exists()条件,不然不知足条件的记录被update称NULL:
好比:stu表存在,但stu1表不存在的数据,对应的字段会被updat成NULL;
*/
-- 2.1 多表关联update单字段
update stu t set t.NAME = (select t1.NAME from stu1 t1 where t1.ID = t.ID)
where exists(select 1 from stu1 t2 where t2.ID = t.ID);
-- 2.2 多表关联update多字段
update stu t set (t.NAME, t.SEX) = (select t1.NAME, t1.SEX from stu1 t1 where t1.ID = t.ID)
where exists(select 1 from stu1 t2 where t2.ID = t.ID);