从服务表中的最新日期更新客户表中的维护日期

问题描述 投票:0回答:1

客户

田野 类型 钥匙 默认 额外
recno int PRI 自动增量
客户密钥 int
维护日期 日期

服务订单

田野 类型 钥匙 默认 额外
recno int PRI 自动增量
客户密钥 int
服务日期 日期

每个客户拥有一条记录。每个客户的服务订单有多个记录。

我如何

UPDATE Customers
将每个客户维护日期记录更新为服务订单中具有最新服务日期的记录?

sql mysql database sql-update relational-database
1个回答
0
投票

这是代码:

Create Table CUSTOMERS (REC_NO INT, CUST_KEY INT, MAINT_DATE DATE);

Insert Into CUSTOMERS 
  Select 1, 100, DATE '2023-12-01' From Dual Union All
  Select 2, 200, DATE '2023-12-10' From Dual Union All
  Select 3, 300, DATE '2023-12-20' From Dual 

Select * From CUSTOMERS
/*
REC_NO  CUST_KEY    MAINT_DATE
    1       100     2023-12-01
    2       200     2023-12-10
    3       300     2023-12-20      */
Create Table SERVICE_ORDERS (REC_NO INT, CUST_KEY INT, SERVICE_DATE DATE);

Insert Into SERVICE_ORDERS 
  Select 1, 100, DATE '2023-12-02' From Dual Union All
  Select 2, 100, DATE '2023-12-12' From Dual Union All
  Select 3, 200, DATE '2023-12-15' From Dual Union All
  Select 4, 300, DATE '2023-12-28' From Dual Union All
  Select 5, 300, DATE '2024-01-04' From Dual Union All
  Select 6, 300, DATE '2024-01-11' From Dual 

Select * From SERVICE_ORDERS
/*
REC_NO  CUST_KEY    SERVICE_DATE
    1       100     2023-12-02
    2       100     2023-12-12
    3       200     2023-12-15
    4       300     2023-12-28
    5       300     2024-01-04
    6       300     2024-01-11      */

更新:

UPDATE CUSTOMERS c 
SET c.MAINT_DATE = (Select Max(SERVICE_DATE) 
                    From SERVICE_ORDERS 
                    Where CUST_KEY = c.CUST_KEY
                   )
WHERE EXISTS (Select 1 From SERVICE_ORDERS Where CUST_KEY = c.CUST_KEY)

Select * From CUSTOMERS
/*
REC_NO  CUST_KEY    MAINT_DATE
    1       100     2023-12-12
    2       200     2023-12-15
    3       300     2024-01-11      */
© www.soinside.com 2019 - 2024. All rights reserved.