SQL关联Orders与Invoices表:获取最新发货日期对应发票ID及最早发货日期
问题修正方案
错误根源
原SQL中max(invoice_id)是按字符串字典序排序取最大的发票ID,没有和「最新发货日期」做绑定,无法满足业务要求——我们需要的是订单下最大发货日期对应那条记录的invoice_id,而不是按字母排序拿最大的invoice_id。
兼容全数据库版本的修正写法(适用于MySQL5.x、PostgreSQL等所有版本)
先聚合每个订单的最早、最新发货日期,再关联回发票表匹配最新发货日期对应的发票ID:
SELECT o.order_id, o.total, i_latest.invoice_id AS latest_invoice_id, i_summary.earliest_ship_date FROM Orders o -- 先按订单聚合,算出最早、最新发货日期 INNER JOIN ( SELECT order_id, MIN(ship_date) AS earliest_ship_date, MAX(ship_date) AS latest_ship_date FROM Invoices GROUP BY order_id ) i_summary ON o.order_id = i_summary.order_id -- 关联回发票表,匹配最新发货日期对应的发票记录 INNER JOIN Invoices i_latest ON i_summary.order_id = i_latest.order_id AND i_summary.latest_ship_date = i_latest.ship_date;
注意:如果同一订单的同一最新发货日期对应多条发票,会输出多行,如需去重可以在SELECT后加
DISTINCT,或者按需取任意一个发票ID。
支持窗口函数的数据库写法(适用于MySQL8+、PostgreSQL、SQL Server等)
用窗口函数按发货日期排序直接取目标发票ID,逻辑更直观:
SELECT o.order_id, o.total, i.latest_invoice_id, i.earliest_ship_date FROM Orders o INNER JOIN ( SELECT order_id, -- 取当前订单下的最早发货日期 MIN(ship_date) AS earliest_ship_date, -- 按发货日期倒序排序,取第一条的发票ID就是最新发货对应的 FIRST_VALUE(invoice_id) OVER ( PARTITION BY order_id ORDER BY ship_date DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS latest_invoice_id FROM Invoices GROUP BY order_id ) i ON o.order_id = i.order_id;
也可以用关联子查询实现同效果的窗口逻辑:
SELECT o.order_id, o.total, i.latest_invoice_id, i.earliest_ship_date FROM Orders o INNER JOIN ( SELECT order_id, MIN(ship_date) AS earliest_ship_date, -- 直接查当前订单最新发货日期对应的发票ID ( SELECT invoice_id FROM Invoices i2 WHERE i2.order_id = i1.order_id ORDER BY ship_date DESC LIMIT 1 ) AS latest_invoice_id FROM Invoices i1 GROUP BY order_id ) i ON o.order_id = i.order_id;
内容的提问来源于stack exchange,提问作者Joe Defill
相关产品推荐
相关产品推荐

