2016-01-09 116 views
0

有兩張表,充值和購買。選擇兩張表mysql不加入

select * from recharge; 
+-----+------+--------+---------------------+ 
| idx | user | amount | created    | 
+-----+------+--------+---------------------+ 
| 1 | 3 |  10 | 2016-01-09 20:16:18 | 
| 2 | 3 |  5 | 2016-01-09 20:16:45 | 
+-----+------+--------+---------------------+ 
select * from purchase; 
+-----+------+----------+---------------------+ 
| idx | user | resource | created    | 
+-----+------+----------+---------------------+ 
| 1 | 3 |  2 | 2016-01-09 20:55:30 | 
| 2 | 3 |  1 | 2016-01-09 20:55:30 | 
+-----+------+----------+---------------------+ 

我想找出用戶的餘額是SUM(金額) - COUNT(purchase.idx)。 (在這種情況下,13)

所以我曾試圖

SELECT (SUM(`amount`)-COUNT(purchase.idx)) AS balance 
FROM `recharge`, `purchase` 
WHERE purchase.user = 3 AND recharge.user = 3 

但是,它返回的錯誤。

+0

哪裏是錯誤? – Sadikhasan

+0

雖然你的代碼寫得不好,會返回錯誤的結果,但不應該導致錯誤。請明確說明錯誤。 –

回答

1

如果你想要一個準確的計數,然後聚合做算術。爲了您的具體情況:

select ((select sum(r.amount) from recharge where r.user = 3) - 
     (select count(*) from purchase p where p.user = 3) 
     ) 

要爲多個用戶做到這一點,將子查詢到from條款或使用union all和聚集。第二是安全,如果用戶可能只在一個表:

select user, coalesce(sum(suma), 0) - coalesce(sum(countp), 0) 
from ((select user, sum(amount) as suma, null as countp 
     from recharge 
     group by user 
    ) union all 
     (select user, null, count(*) 
     from purchase 
     group by user 
    ) 
    ) rp 
group by user 
+0

我更正了錯別字[demo](http://sqlfiddle.com/#!9/89483/7/0) – lad2025

+0

@ lad2025。 。 。謝謝。 –

1

它可以利用工會這樣

SELECT SUM(`amount`-aidx) AS balance 
FROM( 
SELECT SUM(`amount`) as amount, 0 as aidx 
from `recharge` where recharge.user = 3 
union 
select 0 as amount, COUNT(purchase.idx) as aidx 
from `purchase` 
WHERE purchase.user = 3)a 
+0

你忘記了最後的總和[demo](http://sqlfiddle.com/#!9/89483/3/0)。否則,你會得到兩行'15'和'-2' – lad2025