SQL update 多表关联更新

有A、B张表,其记录如下:


A表
c1       c2
--------------
1       a1
2       a2
3       a3
8       a8


B表
c1       c3
--------------
1        b1
2        b1
3        b3
10      b10
A.c1与B.c1相等,用一条sql语句,实现A.c2的值更新为B.c3
---------------------------------------------------------------------------------------

 

语句一

UPDATE A SET A.c2 =B.c3
from A ,B
where A.c1=B.c1

 

语句二
UPDATE    A
SET A.c2 =B.c3
from A inner join B on A.c1=B.c1


注意:

update后面是不能跟多表的,但跟在from子句后面

 

 

 

地址:http://www.cnblogs.com/stublue/archive/2010/08/05/1792977.html

### SQL Update Join Two Tables Syntax and Examples When performing updates across multiple tables using joins, it's important to understand the limitations of certain types of queries. For instance, when an `UPDATE` statement uses a subquery to modify a single table, the optimizer does not employ semijoin or materialization subquery optimizations[^1]. To address this issue, one can rewrite these operations as multi-table `UPDATE` statements utilizing joins instead. For executing cross-table updates effectively in MySQL, both `INNER JOIN` and `LEFT JOIN` are commonly used within the context of an `UPDATE ... JOIN` operation[^2]. #### Using INNER JOIN for Updates An example where only matching records between two tables get updated: ```sql UPDATE employees AS e INNER JOIN departments AS d ON e.department_id = d.id SET e.salary = e.salary * 1.05, e.last_updated = NOW() WHERE d.name = 'Sales'; ``` This query increases salaries by 5% for all employees working under the Sales department while updating the last modified timestamp accordingly. #### Utilizing LEFT JOIN for Updates There might be scenarios like increasing salary for new hires whose performance metrics aren't yet recorded in another related table (e.g., merittable). In such cases, employing a `LEFT JOIN` ensures that even unmatched rows from the primary table (`employees`) receive necessary modifications without being excluded due to lack of corresponding entries elsewhere[^4]: ```sql UPDATE employees AS e LEFT JOIN merit AS m ON e.employee_id = m.emp_id SET e.salary = CASE WHEN m.rating IS NULL THEN e.salary + 500 ELSE e.salary END; ``` Here, every employee gets either no change or receives additional $500 if there isn’t any associated entry found inside the `merit` table regarding their evaluation scores. #### General Guidelines - Always ensure proper indexing on joined columns. - Test changes thoroughly before applying them widely. - Consider transaction management depending upon database requirements.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值