2011-04-13 78 views
0

我在gfee和netpay上得到錯誤的值。mysql上的錯誤值INNER JOIN

SELECT s.id, s.name, c.name AS course_name, 
s.open_bal AS open_balance, sum(i.amount) AS gross_fee, 
sum(i.discount) AS discount, sum(i.amount) - sum(i.discount) AS net_payable, 
SUM(r.reg_fee+r.tut_fee+r.other_fee) AS net_recieved, 
(sum(i.amount) - sum(i.discount)) - SUM(r.reg_fee+r.tut_fee+r.other_fee) AS balance_due 
FROM subscribers s 
INNER JOIN courses c on c.id = s.course_id 
LEFT JOIN invoices i on i.student_id = s.id 
LEFT JOIN recipts r on r.student_id = s.id 
GROUP BY s.id; 

這是怎麼發生的?

+0

你對'錯誤'有什麼意思?你會得到什麼,你期望什麼是正確的? – 2011-04-13 13:32:34

+0

@ypercube我得到了70000作爲gross_fee而不是35000 – seoppc 2011-04-13 13:33:59

+0

聽起來就像你在'recipts'有兩條記錄'student_id'。也許你錯過了一些額外的連接條件? – 2011-04-13 13:37:32

回答

1
SELECT s.id 
    , s.name 
    , c.name AS course_name 
    , s.open_bal AS open_balance 
    , igroup.gross_fee 
    , igroup.discount 
    , igroup.net_payableinvoices 
    , rgroup.net_recieved 
    , igroup.net_payableinvoices - rgroup.net_recieved 
     AS balance_due 
FROM students s 
INNER JOIN courses c 
    on c.id = s.course_id 
LEFT JOIN 
    (SELECT i.student_id 
     , SUM(i.amount) AS gross_fee 
     , SUM(i.discount) AS discount 
     , SUM(i.amount) - sum(i.discount) 
      AS net_payableinvoices 
    FROM invoices i 
    GROUP BY i.student_id 
) AS igroup 
    ON igroup.student_id = s.id 
LEFT JOIN 
    (SELECT r.student_id 
     , SUM(r.reg_fee+r.tut_fee+r.other_fee) 
      AS net_recieved 
    FROM recipts r 
    GROUP BY r.student_id 
) AS rgroup 
    ON rgroup.student_id = s.id 
; 
+0

立即嘗試(放置'i'時出現錯誤)。不知道爲什麼你在錯誤信息中有'fm_invoices'。 – 2011-04-13 14:19:28

+0

它的balance_due爲-15000而不是20000,因爲我得到'gross_fee:35000 |折扣:0 | net_payableinvoices:35000 | net_recieved:15000 | balance_due:-15000' – seoppc 2011-04-13 14:29:02

+0

這是我在那裏去自己去...預彙總所有發票,收據本身並獲得相應的每個學生證一個,然後再加入到學生......很好下崗了。 – DRapp 2011-04-13 14:32:09

1

問題的最可能原因是在一個連接表中存在多行。

既然你得到了兩倍的期望值(70000 vs 35000),我猜想coursesrecipts表中有student_id=22兩行。

+0

yes在收件人中有2行,但如何解決此問題,以及如何優化此代碼以獲得完美結果? – seoppc 2011-04-13 13:41:27

+0

那麼,你需要弄清楚'recipts'表中的哪一行是你計算的那一行。然後,您的連接可以更新爲'left join recipts r on r.student_id = s.id AND r.something = [filter value]'。 – 2011-04-13 13:49:21

+0

我想要所有行(付款欄)在id(從學生表)等於student_id(從recipt表)中的所有行(付款欄)的總和,我想要從該學生收到總付款。 – seoppc 2011-04-13 13:53:46

0

70,000是雙倍35,000的事實是一個非常重要的線索。你在談論一個SUM,你得到了你預期的兩倍。這強烈表明你加入的行數是你認爲的兩倍。

不知道您的架構的細節很難具體,但如果你在receiptsinvoices連接到兩個不同行的每一行(對於這個特定的記錄),你最終有兩個35,000條目列入你的總和。不是你想到的。

+0

我想根據發票,收件人的報告爲您提供所有學生的報告,您可以在我的sql查詢中看到,讓我知道如果您需要我的任何東西,謝謝。 – seoppc 2011-04-13 13:44:12

+0

檢查收件人表的更新問題。 – seoppc 2011-04-13 14:01:15