简体   繁体   中英

select two tables mysql without join

There are two tables, recharge and purchase.

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 |
+-----+------+----------+---------------------+

I want to figure out balance of users which is SUM(amount) - COUNT(purchase.idx). (in this case, 13)

So I had tried

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

but, it returned error.

If you want an accurate count, then aggregate before doing arithmetic. For your particular case:

select ((select sum(r.amount) from recharge where r.user = 3) - 
        (select count(*) from purchase p where p.user = 3)
       )

To do this for multiple users, move the subqueries to the from clause or use union all and aggregation. The second is safer if a user might only be in one table:

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

It is possible to using union like this

SELECT SUM(`amount`-aidx) AS balance
FROM( 
SELECT SUM(`amount`) as amount, 0 as aidx 
from `recharge` where recharge.user = 3
union
select 0 as amount, COUNT(purchase.idx) as aidx 
from `purchase`
WHERE purchase.user = 3 )a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM