根据sql中的列数据加入不同的表

时间:2014-07-29 15:51:46

标签: sql sql-server join

根据加入时使用的单元格中的数据,我有办法将表连接到其他表吗?

我已经注释掉了join循环中的代码,以演示我希望如何处理这个问题。基本上我希望能够将一个表连接到三个表,具体取决于表名。列CK_PaymentTableName只能包含3个字符串:" PaymentCash"," PaymentBank"或" PaymentCard"。

这是我的伪代码:

select 
    st.ID,
    u.Name,
    st.Comment as Comment
from SalesTable st
    inner join Stuff1 s1 on s1.FK_SalesTableID = st.ID
    inner join Unit u on s1.FK_UnitID = u.UnitID
    --left outer join PaymentBank pba on case 
        --when s1.CK_PaymentTableName = 'PaymentBank' 
        --then pba.PaymentBankID else null end = pba.PaymentBankID
    --left outer join PaymentCard pcc on case 
        --when s1.CK_PaymentTableName = 'PaymentCard' 
        --then pcc.PaymentCardID else null end = pcc.PaymentCardID
    --left outer join PaymentCash pca on case 
        --when s1.CK_PaymentTableName = 'PaymentBank' 
        --then pca.PaymentCashID else null end = pca.PaymentCashID
where 
    st.Derp = 'derp'
group by 
    st.ID, 
    st.Comment, 
    u.Name

1 个答案:

答案 0 :(得分:2)

为什么不做一个"和"而不是CASE?基本上你甚至不需要那个。由于它是左连接,如果条件为真,它将有结果。

select 
    st.ID,
    u.Name,
    st.Comment as Comment
from SalesTable st
   inner join Stuff1 s1 on s1.FK_SalesTableID = st.ID
   inner join Unit u on s1.FK_UnitID = u.UnitID
   left outer join PaymentBank pba on s1.CK_PaymentTableName = 'PaymentBank' 
   left outer join PaymentCard pcc on s1.CK_PaymentTableName = 'PaymentCard' 
   left outer join PaymentCash pca on s1.CK_PaymentTableName = 'PaymentCash' 
where 
  st.Derp = 'derp'
group by 
  st.ID, 
  st.Comment, 
  u.Name