0

我创建了一个查询来更新一个字段。但我需要更改最后一条记录的值。在我的ps_order_history表中有date_add列。它的类型是datetime。如果不能在 where 子句中使用 max() 函数,如何获得最后一条记录?这是我到目前为止得到的(有一些固定的参数,但这只是为了测试。我将在 PHP 代码中更改它):

UPDATE ps_order_history AS h 
INNER JOIN ps_order_detail d ON d.id_order = h.id_order
INNER JOIN ps_orders o ON o.id_order = h.id_order
SET h.id_order_state = 18
WHERE d.product_name = "Academia Mastermaq"

AND o.id_customer = (
SELECT id_customer
FROM ps_customer
WHERE firstname = "Cristiano"
AND lastname = "Ferreira dos Santos"
)

AND max(h.date_add)

谢谢。

4

2 回答 2

0

你可以通过使用 Order by xxx DESC LIMIT 1 来做到这一点

于 2013-04-16T12:55:01.187 回答
0

知道了!我发现了 MySQL 中的变量并使用一个变量来存储最大 id_order_history (我意识到我不需要 date_add 列,因为最大 id_order_history 是最后一个数据)。之后,我更新了表格。

这是查询:

SET @maxid = 
(
    SELECT max(h.id_order_history)

    FROM ps_order_history h

    WHERE h.id_order =
    (
        SELECT max(p.id_order)
        FROM ps_orders p
        INNER JOIN ps_order_detail d ON d.id_order = p.id_order

        WHERE p.id_customer = 
        (
            SELECT id_customer
            FROM ps_customer
            WHERE firstname = '$firstname'
            AND lastname = '$lastname'
            LIMIT 1
        )

        AND d.product_name = '$nome_produto'
        AND p.module = 'pagseguro'

        LIMIT 1
    )
);

UPDATE ps_order_history h
SET h.id_order_state = $status
WHERE h.id_order_history = @maxid;
于 2013-04-19T13:44:06.447 回答