代码之家  ›  专栏  ›  技术社区  ›  Mohammad Yusuf

单张桌子上的两个连接

  •  0
  • Mohammad Yusuf  · 技术社区  · 7 年前

    我有两张桌子:

    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
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Squirrel    7 年前

    使用表别名

    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
    
        2
  •  2
  •   DhruvJoshi    7 年前

    考虑在表1上使用左联接两次,如下所示

    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
    
        3
  •  2
  •   Michał Turczyn    7 年前

    加入的备选方案:

    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]