我有两张桌子:
Table1
id acc offacc debit credit
1 43 44 12.2 0
Table2
id dispval
43 ub01
44 cust02
如何在单行中获取此内容:
id acc offacc debit credit
1 ub01 cust02 12.2 0
答案 0 :(得分:4)
使用表别名
select t1.id, t2a.dispval as acc, t2b.dispval as offacc, t1.debit, t1.credit
from Table1 as t1
inner join Table2 as t2a on t2a.id = t1.acc
inner join Table2 as t2b on t2b.id = t1.offacc
答案 1 :(得分:2)
加入的替代方案:
select id,
(select dispval from Table2 where id = [t1].acc) as acc,
(select dispval from Table2 where id = [t1].offacc) as offacc,
debit,
credit
from Table1 [t1]
答案 2 :(得分:2)
考虑在table1上使用两次LEFT JOIN,如下所示
select
t1.id,
acc=t2.dispval,
offacc=t3.dispval,
t1.debit,
t1.credit
from Table1 t1 left join
Table2 t2 on t1.acc=t2.id
Table2 t3 on t1.offacc=t3.id