mysql查詢錯誤 複雜的MySQL查詢錯誤的結果

2021-10-19 19:39:52 字數 2507 閱讀 2703

我正在嘗試構建複雜的

mysql查詢,但它返回錯誤的結果……

select

b.name as batch_name,

b.id as batch_id,

count(distinct s.id)

as total_students,

coalesce( sum(s.open_bal), 0 )

as open_balance,

sum( coalesce(i.reg_fee, 0)

+ coalesce(i.tut_fee, 0)

+ coalesce(i.other_fee, 0)

) as gross_fee,

sum( coalesce(i.discount, 0) )

as discount,

coalesce( sum(s.open_bal), 0 )

+ sum( coalesce(i.reg_fee, 0)

+ coalesce(i.tut_fee, 0)

+ coalesce(i.other_fee, 0)

- sum( coalesce(i.discount, 0) )

as net_payable,

sum( coalesce(r.reg_fee, 0)

+ coalesce(r.tut_fee, 0)

+ coalesce(r.other_fee, 0)

) as net_recieved,

( coalesce( sum(s.open_bal), 0 )

+ sum( coalesce(i.reg_fee, 0)

+ coalesce(i.tut_fee, 0)

+ coalesce(i.other_fee, 0)

- sum( coalesce(i.discount, 0) )

- ( sum( coalesce(r.reg_fee, 0)

+ coalesce(r.tut_fee, 0)

+ coalesce(r.other_fee, 0)

as balance_due

from batches b

left join students s on s.batch = b.id

left join invoices i on i.student_id = s.id

left join recipts r on r.student_id = s.id

where s.inactive = 0

group by b.name, b.id;

返回以下結果……

| batch_name | total_students | open_bal | gross_fee | discount | net_payable | net_recieved | due_balance |

| ms | 6 | 10000 | 0 | 0 | 10000 | 101000 | -91000 |

批次表| id | name |

| 9 | ms |

學生表| id | open_bal | batch | inactive |

| 44 | -16000 | 9 | 0 |

| 182 | 9000 | 9 | 0 |

| 184 | -36000 | 9 | 0 |

| 185 | 19000 | 9 | 0 |

| 186 | 9000 | 9 | 0 |

| 187 | 4000 | 9 | 0 |

發票表| id | student_id | reg_fee | tut_fee | other_fee | net_payable | discount |

上述學生id沒有發票.

收件表| id | student_id | reg_fee | tut_fee | other_fee | status |

| 8 | 44 | 0 | 0 | 1500 | confirmed |

| 277 | 44 | 0 | 50000 | 0 | confirmed |

| 26 | 182 | 0 | 0 | 1500 | confirmed |

| 424 | 182 | 0 | 15000 | 0 | confirmed |

| 468 | 182 | 0 | 15000 | 0 | confirmed |

| 36 | 185 | 0 | 0 | 1500 | confirmed |

| 697 | 185 | 0 | 15000 | 0 | confirmed |

| 66 | 187 | 0 | 0 | 1500 | confirmed |

使用上面的sql查詢和**的預期結果……

| batch_name | total_students | open_bal | gross_fee | discount | net_payable | net_recieved | due_balance |

| ms | 6 | -11000 | 0 | 0 | 10000 | 101000 | -112000 |

mysql複雜查詢的書 mysql 複雜查詢

1.同乙個表下多次查詢 sql語句 select b.select name from exh common.medicine type a where b.p id a.id as p name from exh common.medicine type b 獲取表medicine type中所有...

mysql離散查詢 如何寫出高效能的MySQL查詢

想寫這樣一篇文章很久了,但始終沒有下手。最近幫同事看了幾個查詢,而且自己也在考慮乙個索引系統的問題,所以今天就把這個寫了。介紹一下mysql的索引機制,還有一些mysql查詢的優化策略。鄙人才疏學淺,很可能說的不對,請路過的各位大俠批評指正,獻醜了。首先,說說mysql的索引儲存方式。mysql的索...

mysql中 變數 MYSQL中的變數 MySQL

bitscn.com 只記很基礎的知識,細節東西太麻煩了,而且我也用不到。變數分為使用者變數與系統變數。使用者變數 使用者變數與資料庫連線有關,在這個連線中宣告的變數,在連線斷開的時候,就會消失。在此連線中宣告的變數無法在另一連線中使用。使用者變數的變數名的形式為 varname的形式。名字必須以 ...