sql update join
可使用一个表和连接条件来更新另一个表。
假设有一个客户表,更新包含来自其他系统的最新客户详细信息的客户表。比如要用最新数据来更新客户表。 在这种情况下,将使用客户id上的连接在目标表和源表之间执行连接。
下面来看看sql update
和join
语句的查询语法。
update customer_table
inner join
customer_table
on customer_table.rel_cust_name = customer_table.cust_id
set customer_table.rel_cust_name = customer_table.cust_name
如何在sql update语句中使用join使用多个表?
这里使用两个表:table1
和table2
。
创建table1
表 -
create table table1 (column1 int, column2 int, column3 varchar (100));
insert into table1 (column1, column2, column3)
select 1, 11, 'first'
union all
select 11,12, 'second'
union all
select 21, 13, 'third'
union all
select 31, 14, 'fourth';
创建table2
表 -
create table table2 (column1 int, column2 int, column3 varchar (100));
insert into table2 (column1, column2, column3)
select 1, 21, 'two-one'
union all
select 11, 22, 'two-two'
union all
select 21, 23, 'two-three'
union all
select 31, 24, 'two-four';
接下来,查看表中的内容 -
select * from table1;
执行上面示例代码,得到以下结果 -
mysql> select * from table1;
+---------+---------+---------+
| column1 | column2 | column3 |
+---------+---------+---------+
| 1 | 11 | first |
| 11 | 12 | second |
| 21 | 13 | third |
| 31 | 14 | fourth |
+---------+---------+---------+
4 rows in set
select * from table2;
执行上面示例代码,得到以下结果 -
mysql> select * from table2;
+---------+---------+-----------+
| column1 | column2 | column3 |
+---------+---------+-----------+
| 1 | 21 | two-one |
| 11 | 22 | two-two |
| 21 | 23 | two-three |
| 31 | 24 | two-four |
+---------+---------+-----------+
4 rows in set
在table2
中有两行:column1
的值是21
和31
,假设想要将table1
中的值更新为table2
中column1
为21
和31
行的值。
仅更新column2
和column3
的值。
最简单和最常用的方法是在update
语句中使用join
子句并在update
语句中使用多个表。
update table1 t1
left join table2 t2
on t1.column1 = t2.column1
set t1.column2 = t2.column2,
t1.column3 = t2.column3
where t1.column1 in(21,31);
执行以下语句,查看更新结果 -
mysql> select * from table1;
+---------+---------+-----------+
| column1 | column2 | column3 |
+---------+---------+-----------+
| 1 | 11 | first |
| 11 | 12 | second |
| 21 | 23 | two-three |
| 31 | 24 | two-four |
+---------+---------+-----------+
4 rows in set