SQL更新部分字段或者插入新数据
因为业务的原因,一张表的数据需要整合两张外键关联不强的表数据,这里涉及到更新部分字段或者插入新数据。今天简单的做个笔记,后续有需要再补充完整
测试表结构:
CREATE TABLE `test` (
`id` int(10) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`udex` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
1运行以下sql:
INSERT INTO test2.test (id,name,udex) (SELECT 12,3 FROM tb_alter_plan_log GROUP BY ui_student_id) ON DUPLICATE KEY UPDATE name= VALUES(name);
1运行结果:
2运行以下sql:
INSERT INTO test2.test (id,udex) (SELECT 12,3 FROM tb_alter_plan_log GROUP BY ui_student_id) ON DUPLICATE KEY UPDATE udex = VALUES(udex);
2运行结果:
3运行以下sql:
INSERT INTO test2.test (id,name,udex) (SELECT 13,6,6 FROM tb_alter_plan_log GROUP BY ui_student_id) ON DUPLICATE KEY UPDATE name= VALUES(name),udex = VALUES(udex);
3运行结果:
4运行以下sql:
INSERT INTO test2.test (id,name) (SELECT 13,8 FROM tb_alter_plan_log GROUP BY ui_student_id) ON DUPLICATE KEY UPDATE name = VALUES(name);
4运行结果:
5运行以下sql:
INSERT INTO test2.test (id,udex) (SELECT 13,8 FROM tb_alter_plan_log GROUP BY ui_student_id) ON DUPLICATE KEY UPDATE udex = VALUES(udex);
5运行结果: