5

我有 2 个表(MySQL)

  1. 数据详细信息
  2. account_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)

有人可以帮助我吗,在此先感谢

干杯

同龄人

4

1 回答 1

4

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

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

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
)
于 2011-06-01T08:13:48.690 回答