我有这个ai_invoice
表。
我想选择lastPaymentAmount和lastPaymentDate并引用日期列。
对于lastPaymentDate,我使用MySQL MAX()
这就是我所做的。
SELECT
SUM(ai_account.amount) as amountPaid,
MAX(ai_account.addDate) as lastPaymentDate
FROM ai_account
WHERE ai_account.trader_id = :traderId
我对如何基于lastPaymentDate选择lastPaymentAmount感到困惑。我期待的结果是3434
答案 0 :(得分:2)
这是你必须做的事情
SELECT
ai_account.amount as amountPaid,
ai_account.addDate as lastPaymentDate
FROM ai_account
WHERE ai_account.id = (
SELECT
id
FROM ai_account
WHERE ai_account.trader_id = :traderId
ORDER BY ai_account.addDate DESC
LIMIT 1
)
答案 1 :(得分:2)
SELECT
ai_account.amount as amountPaid,
ai_account.addDate as lastPaymentDate
FROM ai_account
WHERE ai_account.addDate = (SELECT MAX(ai_account.addDate) FROM ai_account
WHERE ai_account.trader_id = :traderId) AND ai_account.trader_id = :traderId;
子查询从ai_account.addDate
中选择最后一个traderId
,并且父WHERE子句将行强制为此日期和此ID。
这可能导致多于一条记录(同一交易商同一天的两个联排)。为了克服这个问题,你可以使用
SELECT
SUM(ai_account.amount) as amountPaid,
MAX(ai_account.addDate) as lastPaymentDate
...