mysql可以使用left连表更新么,使用LEFT JOIN更新MySQL中的多个表

本文探讨了如何使用MySQL的多表UPDATE语句,尤其是在LEFT JOIN场景下,针对T1表中所有LEFT JOIN T2的行进行字段更新。重点介绍了当目标表不能在子查询中使用时,如何利用LEFT JOIN实现效率较低的更新操作,并提供了性能优化建议。
摘要由CSDN通过智能技术生成

I have two tables, and want to update fields in T1 for all rows in a LEFT JOIN.

For an easy example, update all rows of the following result-set:

SELECT T1.* FROM T1 LEFT JOIN T2 ON T1.id = T2.id WHERE T2.id IS NULL

The MySQL manual states that:

Multiple-table UPDATE statements can use any type of join allowed in SELECT statements, such as LEFT JOIN.

But I cannot find the proper syntax for doing that in the documented multiple-tables UPDATE.

What is the proper syntax?

解决方案UPDATE t1

LEFT JOIN

t2

ON t2.id = t1.id

SET t1.col1 = newvalue

WHERE t2.id IS NULL

Note that for a SELECT it would be more efficient to use NOT IN / NOT EXISTS syntax:

SELECT t1.*

FROM t1

WHERE t1.id NOT IN

(

SELECT id

FROM t2

)

See the article in my blog for performance details:

Finding incomplete orders: performance of LEFT JOIN compared to NOT IN

Unfortunately, MySQL does not allow using the target table in a subquery in an UPDATE statement, that's why you'll need to stick to less efficient LEFT JOIN syntax.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值