mysql - 如何在 mysql 中更正此查询当我使用 MAX 时它给了我第一个事务

标签 mysql

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/

相关文章:

php - SQL SELECT 除参数之外的所有内容

mysql - 根据同一表中的其他行更新行

MySQL 求和列并显示列中的最后一行

php - 将遗留 mySQL 数据库集成到新的 Django ORM 支持的数据结构中

php - 文件包含可能存在 PHP 范围问题?

php pdo保存查询数据

python - Django 查询对象的最新版本

java - 可以通过 MySQL Workbench 连接到远程数据库,但不能通过 Java JDBC

php - Msql Select and group from db where team_1 和 team_2 相同但在条目中相反

mysql - MySQL分组索引和单一索引有什么区别