參考地址:https://www.jianshu.com/p/60b3f987c477
1、語法
UPDATE T1 [INNER JOIN | LEFT JOIN] T1 ON T1.C1 = T2. C1 SET T1.C2 = T2.C2, T2.C3 = expr WHERE condition
解析:
(1)、在UPDATE
子句之后,指定主表(T1
)和希望主表連接表(T2
)。
(2)、指定一種要使用的連接,即INNER JOIN
或LEFT JOIN
和連接條件。JOIN
子句必須出現在UPDATE
子句之后。
(3)、要為要更新的T1
表中的列分配新值。
(4)、WHERE子句中的條件用於指定要更新的行。
2、示例
(1)、數據准備
-- 創建user表 CREATE TABLE `user` ( `id` bigint(11) NOT NULL COMMENT '主鍵ID', `name` varchar(30) NOT NULL COMMENT '姓名', `age` int(11) NOT NULL COMMENT '年齡', `email` varchar(50) NOT NULL COMMENT '郵箱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 插入數據 INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('1', 'jane', '18', 'test1@baomidou.com'); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('2', 'Jack', '20', 'test2@baomidou.com'); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('3', 'Tom', '28', 'test3@baomidou.com'); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('4', 'Sandy', '21', 'test4@baomidou.com'); INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('5', 'Billie', '24', 'test5@baomidou.com'); -- 創建user_temp表 CREATE TABLE `user_temp` ( `id` bigint(11) NOT NULL COMMENT '主鍵ID', `name` varchar(30) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年齡', `email` varchar(50) DEFAULT NULL COMMENT '郵箱', `apply_id` int(11) DEFAULT NULL, `user_id` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 插入數據 INSERT INTO `mybaits-plus`.`user_temp` (`id`, `name`, `age`, `email`, `apply_id`, `user_id`) VALUES ('1', NULL, '20', NULL, '1', '1');
(2)、將user_temp表中的數據更新到user表中對應的數據
update user u inner join (select user_id, name,age,email from user_temp where apply_id = 1)b on u.id = b.user_id set u.name = ifnull(b.name,u.name), u.age = ifnull(b.age,u.age), u.email = ifnull(b.email,u.email)
(3)、結果