关联更新
应用场景,A表里面的数据需要更新,但是需要根据B表里面关联的数据进行选择性更新,这时候我们就需要先把数据关联起来,然后更新满足条件的数据
例如,新建两张表: test1 和 test2
CREATE TABLE test1(
id BIGINT(10),
test_name VARCHAR(50),
test_prop_name VARCHAR(30),
test_prop_value VARCHAR(50),
test_prop_id VARCHAR(20)
)
CREATE TABLE test2(
id BIGINT(10),
test_prop_id VARCHAR(20),
test_prop_content VARCHAR(30)
)
然后向两张表里面插入部分测试数据:
INSERT INTO test1(id,test_name,test_prop_name,test_prop_value,test_prop_id)VALUES(1,'aaa','system','itil','1');
INSERT INTO test1(id,test_name,test_prop_name,test_prop_value,test_prop_id)VALUES(2,'bbb','sys','grou','2');
INSERT INTO test1(id,test_name,test_prop_name,test_prop_value,test_prop_id)VALUES(3,'ccc','test','dep','3');
INSERT INTO test1(id,test_name,test_prop_name,test_prop_value,test_prop_id)VALUES(4,'ddd','totl','test','2');
INSERT INTO test1(id,test_name,test_prop_name,test_prop_value,test_prop_id)VALUES(5,'eee','isme','no','4');
INSERT INTO test2(id,test_prop_id,test_prop_content)VALUES(1,'1','系统名称');
INSERT INTO test2(id,test_prop_id,test_prop_content)VALUES(2,'2','系统名称');
更新的时候,我们只需要更新A表中数据的数据中 Id 在B表中也存在的数据
语句我们可以这样写:
UPDATE test1 a JOIN test2 b
ON a.id = b.id
SET a.`test_name`='brady';
完成