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

dzhpxtsq  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(161)

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

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



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

qkf9rpyu

qkf9rpyu1#

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

  1. SELECT *, 'deposit' AS type FROM deposit WHERE status = 'Approved'
  2. UNION ALL
  3. SELECT *, 'withdraw' AS type FROM withdraw WHERE status = 'Approved'

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

  1. WITH alltypes AS (
  2. SELECT *, 'deposit' AS type FROM deposit WHERE status = 'Approved'
  3. UNION ALL
  4. SELECT *, 'withdraw' AS type FROM withdraw WHERE status = 'Approved'
  5. )
  6. SELECT
  7. userid,
  8. name,
  9. email,
  10. SUM(if(type = 'deposit', amount, 0)) AS 'total deposit',
  11. SUM(if(type = 'withdraw', amount, 0)) AS 'total withdraw',
  12. SUM(if(type = 'deposit', amount, -1 * amount)) AS 'net'
  13. FROM alltypes
  14. GROUP BY userid, name, email


这给出了:

  1. +--------+------+---------------+---------------+----------------+------+
  2. | userid | name | email | total deposit | total withdraw | net |
  3. +--------+------+---------------+---------------+----------------+------+
  4. | 1 | fine | [email protected] | 500 | 50 | 450 |
  5. | 4 | new | [email protected] | 20 | 30 | -10 |
  6. +--------+------+---------------+---------------+----------------+------+

展开查看全部

相关问题