我有以下查询
SELECT t1.accountid, t1.accountbalance
FROM transactionstable t1
WHERE transactiondate = (SELECT MAX(transactiondate)
FROM transactionstable
WHERE accountid = t1.accountid);
有没有办法替换第二个选择例如使用having子句,怎么办,因为我需要它快(accountid是一个外键)和transactiondate有一个索引。
谢谢!
答案 0 :(得分:3)
您可以将自JOIN
用于每个accountid
组的最大日期而不是子查询
SELECT t1.accountid,
t1.accountbalance
FROM transactionstable t1
JOIN (SELECT accountid ,MAX(transactiondate) transactiondate
FROM transactionstable
GROUP BY accountid ) t
USING (transactiondate ,accountid )
transactiondate ,accountid
上的复合索引也是有帮助的
create index my_idx on my_table(transactiondate ,accountid);