我想获取订单状态,其中状态记录在单独的表“ order_status_change”中。使用以下脚本,我可以获取所有记录,但不能获取最新状态。 (最大(状态更改日期)的order_item_ID需要状态。
SET @UserID = 160;
SET @OrderDateTime = '2018-11-13 09:23:45';
SELECT
order_items.ORDER_ITEM_ID,
order_price.ORDER_ITEM_TOTAL_PRICE,
order_status_change.ORDER_STATUS
FROM order_items
INNER JOIN order_price ON order_price.ORDERP_ITEM_ID = order_items.ORDER_ITEM_ID
INNER JOIN order_status_change ON order_status_change.ORDER_ITEM_ID = order_items.ORDER_ITEM_ID
WHERE ((SELECT A.A_User_ID from A WHERE A.A_USER_ID = @UserID) AND (DATE(order_items.ORDER_REQUIRED_DATE_TIME) = DATE(@OrderDateTime)))
如果我使用Max(order_status_change.STATUS_CHANGE_DATE),那么我只会得到一条记录。 我通过在这里查看其他示例来修改查询,但是没有用。
SELECT
order_items.ORDER_ITEM_ID,
order_price.ORDER_ITEM_TOTAL_PRICE,
order_status_change.ORDER_STATUS
FROM order_items
INNER JOIN order_price ON order_price.ORDERP_ITEM_ID = order_items.ORDER_ITEM_ID
INNER JOIN
(SELECT MAX(order_status_change.ORDER_STATUS_CHANGE_DATETIME) AS STATUS_CHANGED_DATE FROM order_status_change WHERE order_status_change.ORDER_ITEM_ID = order_items.ORDER_ITEM_ID)
AS order_status_change ON order_status_change.ORDER_ITEM_ID = order_items.ORDER_ITEM_ID
WHERE ((SELECT A.A_User_ID from A WHERE A.A_User_ID = @UserID) AND (DATE(order_items.ORDER_REQUIRED_DATE_TIME) = DATE(@OrderDateTime)))
如何获取每个order_items.ORDER_ITEM_ID的“最新” order_status_change.STATUS?
答案 0 :(得分:1)
您可以尝试一下。
SELECT
order_items.ORDER_ITEM_ID,
order_price.ORDER_ITEM_TOTAL_PRICE,
order_status_change.ORDER_STATUS
FROM order_items
INNER JOIN order_price ON order_price.ORDERP_ITEM_ID = order_items.ORDER_ITEM_ID
INNER JOIN
(
SELECT MAX(order_status_change.ORDER_STATUS_CHANGE_DATETIME) AS STATUS_CHANGED_DATE,ORDER_ITEM_ID
FROM order_status_change
GROUP BY ORDER_ITEM_ID
) AS order_status_change ON order_status_change.ORDER_ITEM_ID = order_items.ORDER_ITEM_ID
WHERE (
(DATE(order_items.ORDER_REQUIRED_DATE_TIME) = DATE(@OrderDateTime))
)