mysql INNER JOIN 上的值错误
我得到的 gfee 和 netpay 值错误。
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;
为什么会发生这种情况?
I am getting the wrong value on gfee and netpay.
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;
Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
70,000 是 35,000 的两倍这一事实是一个非常重要的线索。您正在谈论
SUM
并且您得到的结果是您预期的两倍。这强烈表明您加入的行数是您想象的两倍。如果不了解架构的详细信息,则很难具体说明,但如果您要为
invoices
中的每一行(对于此特定记录)连接到receipts
中的两个不同行,您最终会在总和中包含两个35,000
条目。不是你想的那样。The fact that 70,000 is double 35,000 is a hugely important clue. You're talking about a
SUM
and you're getting twice what you expected. That suggests strongly that you're joining to twice as many rows as you think you are.Without knowing the details of your schema it's hard to be specific, but if you're joining to two different rows in
receipts
for each row ininvoices
(for this particular record), you end up with two35,000
entries included in your sum. Not what you had in mind.问题最可能的原因是连接表之一中存在多行。
由于您获得的值恰好是预期值的两倍(70000 与 35000),我猜测在
courses
或recipts
表中有两行带有student_id=22
。The most likely cause of your problem is multiple rows existing in one of the joined tables.
Since you are getting exactly twice your expected value (70000 vs 35000) I would guess that there are two rows in either the
courses
orrecipts
tables withstudent_id=22
.