Sql简介 专题
专题目录
您的位置:database > Sql简介专题 > SQL Update与Join
SQL Update与Join
作者:--    发布时间:2019-11-20

sql update join可使用一个表和连接条件来更新另一个表。

假设有一个客户表,更新包含来自其他系统的最新客户详细信息的客户表。比如要用最新数据来更新客户表。 在这种情况下,将使用客户id上的连接在目标表和源表之间执行连接。

下面来看看sql updatejoin语句的查询语法。

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使用多个表?

这里使用两个表:table1table2

创建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的值是2131,假设想要将table1中的值更新为table2column12131行的值。

仅更新column2column3的值。

最简单和最常用的方法是在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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册