![](/img/trans.png)
[英]MYSQL: Combine two different tables and calculate SUM of one column and GROUP BY two columns
[英]SUM two columns of two different tables in one result based group by id of another table
我有3張桌子:
用戶:
id | account_name
-------------------|----------------------|
18 | panic |
存款:
id | user_id | amount
-------------------|---------------------------|
1 | 18 | 100
2 | 18 | 100
提款:
id | user_id | amount
------------------------|--------------------------------|
1 | 18 | 200
2 | 18 | 200
我正在嘗試獲得如下結果:
id | totalDeposits | totalWithdraws
------------------------|---------------------------|
18 | 200 | 400
現在,當我出於某種原因嘗試獲取總數時,它們會交叉相加,當然,如果沒有行,它應該返回 0。
SELECT t0.id,IFNULL(SUM(t1.amount),0) AS totalWithdrawals,
IFNULL(SUM(t2.amount),0) AS totalDeposits
FROM users t0
LEFT OUTER JOIN withdrawals t1 ON (t0.id = t1.user_id)
LEFT OUTER JOIN deposits t2 ON (t0.id = t2.user_id)
GROUP BY t0.id
知道如何進行這種交叉連接或我在哪里總結錯誤嗎?
嘗試這個-
SELECT A.id,
(SELECT SUM(amount) FROM Deposits WHERE user_id = A.id) totalDeposits,
(SELECT SUM(amount) FROM Withdrawals WHERE user_id = A.id) totalWithdraws
FROM users A
WHERE A.id = 18 -- WHERE can be removed to get all users details
你可以嘗試一些類似的東西
SELECT u.id,
COALESCE(d.amount, 0) totalDeposits,
COALESCE(w.amount, 0) totalWithdrawals
FROM users u
LEFT JOIN (
SELECT user_id, SUM(amount) amount
FROM deposits
GROUP BY user_id
) d ON u.id = d.user_id
LEFT JOIN (
SELECT user_id, SUM(amount) amount
FROM withdrawals
GROUP BY user_id
) w ON u.id = w.user_id
結果:
| id | totalDeposits | totalWithdrawals | |----|---------------|------------------| | 18 | 200 | 400 |
問題是您正在生成笛卡爾積。 一種解決方案是先聚合。 另一種方法是使用UNION ALL
和GROUP BY
。 我會將其結構為:
SELECT u.id,
SUM(deposit) as deposits,
SUM(withdrawal) as withdrawal
FROM users u LEFT JOIN
((SELECT d.user_id, d.amount as deposit, 0 as withdrawal
FROM deposits d
) UNION ALL
(SELECT w.user_id, 0, w.amount
FROM withdrawals w
)
) dw
ON u.id = dw.user_id
GROUP BY u.id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.