SQL涉及4个一对多表

时间:2013-08-19 05:00:09

标签: sql relationship

我有以下查询,但没有给出我想要的输出:

   SELECT DBO.[PLAN].DATE, 
       DBO.TBRECEIPT.RECEIPTDATE, 
       DBO.TBRECEIPTLINE.RECEIPTQTY, 
       DBO.PLAN_LINE.PALLETS 
FROM   DBO.TBRECEIPT 
       INNER JOIN DBO.TBRECEIPTLINE 
               ON DBO.TBRECEIPT.PKID = DBO.TBRECEIPTLINE.RECEIPTID 
       INNER JOIN DBO.[PLAN] 
                  INNER JOIN DBO.PLAN_LINE 
                          ON DBO.[PLAN].PKID = DBO.PLAN_LINE.PLANID 
               ON DBO.TBRECEIPT.RECEIPTDATE = DBO.[PLAN].DATE 

我必须错误地将这两组标题/折线表联系起来 有人能发现错误吗?

由于

1 个答案:

答案 0 :(得分:0)

SELECT DBO.[PLAN].DATE, 
       DBO.TBRECEIPT.RECEIPTDATE, 
       DBO.TBRECEIPTLINE.RECEIPTQTY, 
       DBO.PLAN_LINE.PALLETS 
FROM   DBO.TBRECEIPT 
       INNER JOIN DBO.TBRECEIPTLINE 
               ON DBO.TBRECEIPT.PKID = DBO.TBRECEIPTLINE.RECEIPTID 
       INNER JOIN DBO.[PLAN] 
                  --No Condition? Problem 
                  INNER JOIN DBO.PLAN_LINE 
                          ON DBO.[PLAN].PKID = DBO.PLAN_LINE.PLANID 
               ON DBO.TBRECEIPT.RECEIPTDATE = DBO.[PLAN].DATE 

试试这个:我建议您使用 ALIAS 表格以获得更好的代码实践。

SELECT P.DATE, 
       R.RECEIPTDATE, 
       RL.RECEIPTQTY, 
       PL.PALLETS 
FROM   DBO.TBRECEIPT R 
       INNER JOIN DBO.TBRECEIPTLINE RL 
               ON R.PKID = RL.RECEIPTID 
       INNER JOIN DBO.[PLAN] P 
               ON R.RECEIPTDATE = P.DATE 
       INNER JOIN DBO.PLAN_LINE PL 
               ON P.PKID = PL.PLANID