Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据sql中的列数据连接不同的表_Sql_Sql Server_Join - Fatal编程技术网

根据sql中的列数据连接不同的表

根据sql中的列数据连接不同的表,sql,sql-server,join,Sql,Sql Server,Join,是否有一种方法可以根据联接中使用的单元格中的数据将表联接到其他表 我已经注释掉了join循环中的代码,以演示如何处理这个问题。基本上,我希望能够根据表名将一个表连接到三个表中的任何一个。列CK_PaymentTableName只能包含三个字符串之一:“PaymentCash”、“PaymentBank”或“PaymentCard” 这是我的伪代码: select st.ID, u.Name, st.Comment as Comment from SalesTable s

是否有一种方法可以根据联接中使用的单元格中的数据将表联接到其他表

我已经注释掉了join循环中的代码,以演示如何处理这个问题。基本上,我希望能够根据表名将一个表连接到三个表中的任何一个。列CK_PaymentTableName只能包含三个字符串之一:“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
为什么不做一个“And”而不是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

你到底要参加什么?看起来您在Stuff1和付款表之间没有链接。动态sql是选项吗?如果是这样的话,可以根据条件构建连接。您可以在连接中使用case语句对不起,我的缩写代码。我实际上试图使用
case
语句,但我可以让它们为我的加入语句工作。但是没有,我的SalesTable没有PaymentId。对paymentType的唯一引用在Stuff1表中,它只有上面提到的3个字符串a。是否有任何付款表具有销售id?你希望如何正确地加入数据?我想我把我的思维过程复杂化了@TMNT2014感谢您提醒我,有时我们需要自下而上开始。谢谢