如何在一个表中添加和减去具有不同condtion的数据

时间:2016-06-03 10:16:31

标签: php mysql

我有一个三个表,一个是Userregistration,第二个是撤销,第三个是来自walletbalance表的walletbalance我必须添加所有贷记余额和借方余额,然后从借记余额中扣除贷记余额以获得实际余额并从所有三个中检索数据tables.Below是我的表结构。

用户注册表

........................................
id      fullname   mobile_no       email
.........................................
5      varun         12344567   abc@gmail
6      nitin         12345678   def@gmail

撤回

...............................
wid   userid    withdraw_status
...............................
1     5         pending
2     6         pending

walletbalance

..........................................
id   user_id   balance  transaction_type
..........................................
1      5       100        credit
2      5       20         debit
3      6       200        credit
4      6       100        debit

我想要这个输出:

.................................................................
wid  user_id balance  withdraw_status  fullname  mobile_no  email
.................................................................
1     5        80       pending        varun     12344567   abc@gmail
2     6        100      pending        nitin     12344567   def@gmail

我试过这个以找到用户的实际余额,但我无法做到 啊,这个。

SELECT SUM(`balance`) as b1 from walletbalance WHERE `user_id`='5' and `transaction_type`='credit' UNION SELECT SUM(`balance`) as b2 from walletbalance WHERE `user_id`='5' and `transaction_type`='debit'

1 个答案:

答案 0 :(得分:1)

SELECT t2.wid, t2.userid AS user_id, t3.balance, t2.withdraw_status,
    t1.fullname, t1.mobile_no, t1.email    
FROM Userregistration t1
INNER JOIN withdraw t2
    ON t1.id = t2.userid
INNER JOIN
(
    SELECT user_id,
        SUM(CASE WHEN transaction_type = 'credit'
                 THEN balance
                 ELSE balance * -1
            END) AS balance
    FROM walletbalance
    GROUP BY user_id
) t3
    ON t1.id = t3.user_id