2011-04-13 235 views
1

我使用以下查詢來獲取不同的表我的數據庫,檢查報告如下......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 students 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; 

發票

| id | student_id | amount | discount | dnt  | 
+----+------------+----------+----------+-------------+ 
| 2 | 22   | 35000 | 0  | 2011/01/01 | 
+----+------------+----------+----------+-------------+ 

沒有得到來自gross_fee和net_payable正確的值。

謝謝。

+1

GROUP BY s.id也許? – 2011-04-13 11:45:35

+0

你能改變你的代碼嗎? – seoppc 2011-04-13 11:48:19

+0

嘗試將'INNER'改爲'LEFT'加入並分享結果 – Teneff 2011-04-13 11:50:21

回答

2

鑑於SUM s在選擇我想GROUP BY s.id應該做的伎倆。反正一個GROUP BY似乎缺少:)

SELECT s.id, s.name, c.name AS course_name, 
s.open_bal AS open_balance, 
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 students 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; 

編輯

單獨的查詢允許檢索gross_feenet_payable所有發票

SELECT sum(amount) AS gross_fee, 
    sum(discount) AS discount, 
    sum(amount) - sum(discount) AS net_payable, 
FROM invoices; 
+0

感謝您的答案和權利我錯過了GROUP By,你可以再次檢查代碼,看看我是否有任何錯誤,或者我可以優化此代碼。 – seoppc 2011-04-13 11:56:52

+0

@Frosty Z它甚至給我錯誤的gross_fee和net_payable的價值。 – seoppc 2011-04-13 12:10:20

+0

看起來不錯。不過很多SUM。如果您遇到「GROUP BY」的性能問題,請參閱http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html http://dev.mysql。 com/doc/refman/5.0/zh/group-by-optimization.html – 2011-04-13 12:11:11

0

同時擁有學生記錄得到的值爲s.course_id?

你有一個內從學生的課程加入...

INNER JOIN橫列C上c.id = s.course_id

如果s.course_id中的學生記錄爲null ,查詢將只返回一行。

+0

是的,都有價值,我應該改變代碼? – seoppc 2011-04-13 12:11:13