mysql - 选择两个没有连接的表mysql

标签 mysql sql select

有两个表,充值和购买。

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(amount) - COUNT(purchase.idx)。 (在本例中为 13)

所以我试过了

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

但是,它返回错误。

最佳答案

如果你想要一个准确的计数,那么做算术之前聚合。对于您的特定情况:

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

关于mysql - 选择两个没有连接的表mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693490/

相关文章:

mysql - 优化包含子选择的 MySQL 查询

java - 如何?使用 Retrofit2 将当前日期从 Android 插入到 mySQL 数据库中

SQLite基于时间格式的SELECT记录 "HH:mm:ss"

sql - 多次选择同一列

python - 如何在python中的两个值之间选择一个列表 block

mysql - Eloquent belongsToMany 和三表(包括 Pivot)

android - eclipse中连接在线mysql数据库

java - postgresql 错误接近于 java

sql - 如何在 postgres 中使用动态标识符连接表?

sql - 展平枚举表中的 T-SQL 位掩码