如何实现两个表左连接的Mysql Union

问题描述 投票:0回答:1

有存款表

然后有提款表

我必须创建一个 mysql 查询,以便我有列 用户 ID、姓名、电子邮件、总存款、总提款和净额(总存款 - 总提款) 对于上面两个表中的给定日期范围 状态为已批准 根据网络订购

对于某个用户id,提款表中有记录,但充值表没有记录,则相应期间的提款总额为0 反之亦然 如果某个用户 ID 的存款表中有记录,但提款表中没有记录,那么对于此类用户,相应期间的提款总额为 0

如何用MYSQL查询实现这一点

mysql join mysqli left-join union
1个回答
0
投票

首先,准备一个数据集,该数据集是两个表的并集,但仅包含“已批准”记录:

SELECT *, 'deposit' AS type FROM deposit WHERE status = 'Approved'
UNION ALL
SELECT *, 'widthdraw' AS type FROM withdraw WHERE status = 'Approved'

然后您可以从该数据集中进行选择,并带有一些条件总和:

WITH alltypes AS (
    SELECT *, 'deposit' AS type FROM deposit WHERE status = 'Approved'
    UNION ALL
    SELECT *, 'widthdraw' AS type FROM withdraw WHERE status = 'Approved'
)
SELECT
    userid,
    name,
    email,
    SUM(if(type = 'deposit', amount, 0)) AS 'total deposit',
    SUM(if(type = 'withdraw', amount, 0)) AS 'total withdraw',
    SUM(if(type = 'deposit', amount, -1 * amount)) AS 'net'
FROM alltypes
GROUP BY userid, name, email

这给出:

+--------+------+---------------+---------------+----------------+------+
| userid | name | email         | total deposit | total withdraw | net  |
+--------+------+---------------+---------------+----------------+------+
|      1 | fine | [email protected] |           500 |              0 |  450 |
|      4 | new  | [email protected]   |            20 |              0 |  -10 |
+--------+------+---------------+---------------+----------------+------+
© www.soinside.com 2019 - 2024. All rights reserved.