我有两张桌子。帐户表和事务表。我想列出所有帐户的上次交易。需要左连接,因为可能存在没有事务的情况。
我有类似
的东西select * from Account ac left join Transaction trans on ac.id = trans.acc_id
但这将列出所有交易数据。不知道我怎么能修改它。
答案 0 :(得分:2)
您可以尝试加入Account表,只包含您的Transaction表中与每个acc_id的最大ID相对应的acc_id:
select ac.*, t.* from Account ac left join (select acc_id, max(id) from Transaction group by acc_id) trans on ac.id = trans.acc_id left join Transaction t on trans.id=t.id
答案 1 :(得分:2)
第一个左连接会获取该帐户的最后一个\ max事务ID。第二个左连接将获取最后一个ID的所有交易信息。
select ac.*, lasttrans.*
from Account ac
left join (select acc_id, max(id) as id from Transaction group by acc_id) transmax
on ac.id = transmax.acc_id
left join Transaction lasttrans on lasttrans.id = transmax.id
答案 2 :(得分:0)
只需使用aggregate
功能以及group by
select * from
from Account ac left join Transaction trans
on ac.id = trans.acc_id
where trans.id in (select max(id) from trans group by ac.id)
id或日期,您希望获得max
...
答案 3 :(得分:0)
这接近你的预期吗?
with acc as
(select 1 acc_id, 'name1' acc_name from dual union
select 2 acc_id, 'name2' acc_name from dual union
select 3 acc_id, 'name3' acc_name from dual),
trans as
(select 1 trans_id, 1 trans_acc_id, 'transaction detail 1' transdtl from dual
union
select 2 trans_id, 1 trans_acc_id, 'transaction detail 2' transdtl from dual
union
select 3 trans_id, 1 trans_acc_id, 'transaction detail 3' transdtl from dual
union
select 4 trans_id, 3 trans_acc_id, 'transaction detail 4' transdtl from dual
union
select 5 trans_id, 5 trans_acc_id, 'transaction detail 5' transdtl from dual
)
select * from acc, trans
where acc.acc_id = trans.trans_acc_id
and trans.trans_id in (select max(trans_id) from trans inner_trans where
inner_trans.trans_acc_id = acc.acc_id)
回应是:
ACC_ID|ACC_NAME|TRANS_ID|TRANS_ACC_ID|TRANSDTL
1 |name1 |3 |1 |transaction detail 3
3 |name3 |4 |3 |transaction detail 4