查看表,如果情况不正确

时间:2019-01-14 10:57:28

标签: php mysql laravel-5

查看表:无法正常工作。 我有两个桌子

  1. Deposits

  2. withdraws

如果:

Account no  = 101
balance = 100 $
Account no  = 102 
balance = 50 $

当我withdraw某人money像该帐户时A/C 101提取金额10$
现在结果是:减去所有帐户余额

当前余额:

Account no  = 101
balance = 90 $ -10 $ 
Account no  = 102 
balance = 40 $ -10 $ // But 50

每个帐户减去存款余额

CREATE VIEW main_balance_new as select account_no as account_no,
 SUM(deposit_amount)-(select 
  CASE 
    WHEN withdraw_amount IS NULL THEN 0
   ELSE SUM(withdraw_amount)
  END
  from withdraws) as balance from deposits group by account_no 

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为您需要分别汇总存款和取款表:

CREATE VIEW d_view AS
SELECT account_no, SUM(deposit_amount) AS deposit_sum
FROM deposits
GROUP BY account_no

CREATE VIEW w_view AS
SELECT account_no, SUM(withdraw_amount) AS withdraw_sum
FROM withdraws
GROUP BY account_no

CREATE VIEW main_balance_new AS
SELECT
    d.account_no,
    d.deposit_sum - COALESCE(w.withdraw_sum, 0) AS balance
FROM d_view d
LEFT JOIN w_view w
    ON d.account_no = w.account_no;

此答案使给定帐户仅出现在存款表中而不出现在取款表中的可能性。

编辑:

如果需要视图,请使用单独的视图来解决子查询问题。