如何在两个表上使用左连接实现Mysql Union [已关闭]

dzhpxtsq  于 5个月前  发布在  Mysql
关注(0)|答案(1)|浏览(48)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

18天前关门了。
Improve this question
有一个存款表
x1c 0d1x的数据
然后是取款台



我必须创建一个mysql查询,使我有列用户名,姓名,电子邮件,总存款,总提款和净(总存款-总提款)为一个给定的日期范围从上述两个表的状态为批准订购的基础上净
对于一个用户ID,取款表中有记录,但存款表中没有记录,则相应期间的取款总额为0,反之亦然,如果对于一个用户ID,存款表中有记录,但取款表中没有记录,则相应期间的取款总额为0
如何用MYSQL实现这个查询

qkf9rpyu

qkf9rpyu1#

首先,准备一个数据集,它是两个表的UNION,但只包括“Approved”记录:

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

字符串
然后你可以从这个数据集中选择,使用一些条件和:

WITH alltypes AS (
    SELECT *, 'deposit' AS type FROM deposit WHERE status = 'Approved'
    UNION ALL
    SELECT *, 'withdraw' 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 |             50 |  450 |
|      4 | new  | [email protected]   |            20 |             30 |  -10 |
+--------+------+---------------+---------------+----------------+------+

相关问题