Is there a way for me to join a table to other tables depending on the data in the cell used in the joining?
I have commented out the code in the join loop to demonstrate how I would want to approach this issue. Basically I want to be able to join one table to either three tables depending on the table name. The column CK_PaymentTableName can only contain either of 3 strings: "PaymentCash", "PaymentBank" or "PaymentCard".
Here is my pseudo code:
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
Why not Just do an "And" Instead of the CASE? Essentially you dont even need that. Since it is a left Join it will have results if the condition is true.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.