【问题标题】:MySQL batch updateMySQL批量更新
【发布时间】:2011-09-06 02:03:46
【问题描述】:

我有 2 个表(MySQL)

  1. data_details
  2. accounts_invoices

理想情况下,每个 data_details 都应该有一个 accounts_invoices id。 (data_details 有一个外键和accounts_invoices 的主键)

由于某些原因,data_details 记录中accounts_invoice_id 不存在于accounts_invoices 表中

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

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)

谁能帮帮我,提前谢谢

干杯

同人

【问题讨论】:

  • 为了以后避免这个问题,我推荐使用 InnoDB 和外键约束。
  • 嗨@Znarkus,感谢您的评论,基本上我也在尝试向这个现有表添加外键关系:D(data_details)
  • 未测试,但 mysql 允许查询:UPDATE data_details SET d1 account_invoice_id=1 FROM data_details d1 INNER JOIN data_details d2 ON d1.account_invoice_id = d1.id LEFT JOIN accounts_invoices a on d2.account_invoice_id = a.id WHERE a.id 为空
  • 嗨@Brice,谢谢你的回答......但我收到了这个错误......错误1064(42000):你的SQL语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的“FROM data_details d1 INNER JOIN data_details d2 ON d1.account_invoice_id = d1.id”附近使用正确的语法有什么想法吗??
  • oups 对不起,我认为这是 ON d1.account_invoice_id = d2.id

标签: mysql sql sql-update mysql-error-1093


【解决方案1】:

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

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 以修复我在 cmets 中发现的错误。

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
)

【讨论】:

  • 嗨@Znarkus,这工作没有错误,但没有更新..有什么想法吗?谢谢你的帮助欢呼sameera
  • 尝试提取select 语句,看看它们返回什么
  • Hi Select 语句返回正确的 id 作为 id.. 所以选择是正确的.. 所以它不仅仅是更新记录.. 任何帮助将不胜感激,谢谢
  • 是的......它工作......我只是将 where 条件更改为 account_invoice_id 到 id......非常感谢......
猜你喜欢
  • 1970-01-01
  • 2023-01-14
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
相关资源
最近更新 更多