MySQL批量更新

前端之家收集整理的这篇文章主要介绍了MySQL批量更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有2个表(MySQL)

> data_details
> accounts_invoices

理想情况下,每个data_details都应具有accounts_invoices id. (data_details有一个带有accounts_invoices主键的外键)

由于某种原因,有data_details记录,其中accounts_invooice表中不存在accounts_invoice_id

所以我尝试用已知的accounts_invoice id更新那些data_details记录.这就是我做的

@H_404_15@update data_details 
set account_invoice_id = 1
where account_invoice_id in (
  select d.id
  from data_details d left join accounts_invoices a
  on d.account_invoice_id = a.id
  where a.id is null    
)

但是说出错了

您可以在FROM子句中指定目标表’data_details’以进行更新(错误1093)

有人可以帮助我,提前谢谢

干杯

sameera

最佳答案
现在这可能是一个疯狂的猜测,但我认为问题是你更新了你正在查询的同一个表.我认为解决方法是使用临时表,如下所示:

@H_404_15@update data_details 
set account_invoice_id = 1
where account_invoice_id in (
select * from (
  select d.id
  from data_details d left join accounts_invoices a
  on d.account_invoice_id = a.id
  where a.id is null    
) as t
)

虽然没试过,所以可能都错了.

更新了sql以修复我在注释中发现的错误.

@H_404_15@update data_details 
set account_invoice_id = 1
where id in (
select * from (
  select d.id
  from data_details d left join accounts_invoices a
  on d.account_invoice_id = a.id
  where a.id is null    
) as t
)
原文链接:https://www.f2er.com/mysql/433014.html

猜你在找的MySQL相关文章