如何在内部join语句中获取最大日期

xriantvc  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(231)

我想获取订单状态,其中状态记录在单独的表“订单\状态\更改”中。使用下面的脚本,我可以得到所有的记录,但不能得到最新的状态(需要最大订单\项目\ 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\u status\u change.status\u change\u 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)))

如何获取每个订单\项目\订单\项目\ id的“最新”订单\状态\更改.status?

bq8i3lrv

bq8i3lrv1#

你可以试试这个。

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))
)

相关问题