SQL Update的四種常見寫法

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);
相關文章
相關標籤/搜索