使用maxdate更新行,其中给出了select中的id和select中的maxdate

时间:2018-11-23 21:36:56

标签: mysql sql-update

我有一条select语句,该语句返回一组ID和一个maxdate。现在,我要使用给定的发票ID的给定的maxdate更新发票表中的performance_date。

Select invoices.id, max(invoicepositions.performance_date) as maxdate
from invoices
inner join invoicepositions on invoices.id = invoicepositions.invoice_id
where invoices.performance_date IS NULL
group by invoices.id

(MySQL)怎么可能?

1 个答案:

答案 0 :(得分:1)

您可以将当前的SELECT查询用作Derived Table,并使用Join将其invoicesid表中,然后进行更新。

UPDATE invoices AS i 
JOIN
(
  Select invoices.id, max(invoicepositions.performance_date) as maxdate
  from invoices
  inner join invoicepositions on invoices.id = invoicepositions.invoice_id
  where invoices.performance_date IS NULL
  group by invoices.id
) AS dt 
  ON dt.id = i.id 
SET i.performance_date = dt.maxdate