SELECT a.accountid,a.accountname, IFNULL(accountbalance,0)
FROM transactionstable tt
JOIN (SELECT accountid ,MAX(transactiondate) transactiondate
FROM transactionstable
WHERE transactiondate<"2014-04-16"
GROUP BY accountid ) t
USING (transactiondate ,accountid )
RIGHT JOIN allaccounts a ON (tt.accountid=a.accountid)
GROUP BY a.accountid
ORDER BY a.accountname ;
我有很多交易(transactiondate,accountid)所以它不是唯一的,我需要最后一笔交易(transactionid 是唯一的)但我不知道在哪里添加它例如:
trnx id accountid date accbalance
1 222 2014-04-16 2000
2 222 2014-04-16 1900
3 222 2014-04-16 1850
4 ...
所以我需要得到最后的余额:1850,而我得到第一个余额 2000:/
非常感谢你的帮助
编辑
我得到了正确的答案,但它花费了太多时间(37 秒,因为该表包含大约 400 万条记录):
SELECT a.accountid,a.accountname, IFNULL(accountbalance,0)
FROM transactionstable tt
JOIN (SELECT accountid ,MAX(transactiondate) transactiondate,MAX(transactionid) transactionid
FROM transactionstable
WHERE transactiondate<"2014-04-15 23:59:59"
GROUP BY accountid
HAVING MAX(transactiondate) ) t
USING ( transactionid )
RIGHT JOIN allaccounts a ON (tt.accountid=a.accountid)
ORDER BY a.accountname ;
最佳答案
您可以使用 not exists
获取最后一笔交易的方法更轻松地执行此逻辑:
SELECT a.accountid, a.accountname, IFNULL(accountbalance,0)
FROM allaccounts a LEFT JOIN
transactionstable tt
ON tt.accountid = a.accountid
WHERE NOT EXISTS (SELECT 1
FROM transactionstable tt2
WHERE tt2.accountid = tt2.accountid and
(tt2.transactiondate > tt.transactiondate or
tt2.transactiondate = tt.transactiondate and
tt2.trans_id > tt.trans_id
)
)
ORDER BY a.accountname;
编辑:
如果你可以只使用transactionid
,那么试试这个:
SELECT a.accountid, a.accountname, IFNULL(accountbalance,0)
FROM allaccounts a LEFT JOIN
transactionstable tt
ON tt.accountid = a.accountid
WHERE NOT EXISTS (SELECT 1
FROM transactionstable tt2
WHERE tt2.accountid = tt.accountid and
tt2.transactionid > tt.transactionid
)
ORDER BY a.accountname;
并且,还在 transactiontable(accountid, transactionid)
上创建一个索引。
关于mysql - 如何在 mysql 中更正此查询当我使用 MAX 时它给了我第一个事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23105757/