SELECT User.username,
IFNULL(SUM(credit) - SUM(debit), 0) AS total,
( SELECT SUM(Bid.credit) - SUM(Bid.debit) AS freebids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
WHERE Bid.type = 2
) AS FreeBids,
( SELECT SUM(Bid.credit) - SUM(Bid.debit) AS Normalbids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
WHERE Bid.type = 0
OR Bid.type = 1
) AS NormalBids
FROM users AS User
LEFT
JOIN bids AS Bid
ON Bid.user_id = User.id
GROUP
BY User.id
here is my sample table:
for users
id username
1 user1
2 user2
3 user3
4 user4
For bids
id user_id debit credit type
1 1 0 10 0
2 1 1 5 2
3 1 1 0 2
4 3 0 10 0
6 2 0 10 0
7 4 1 10 0
8 4 1 0 1
But I am having problem in displaying the subquery (Freebids and Normalbids) are all has the same value here are the sample display:
username total FreeBids NormalBids
user1 10 12809 965
user2 20 12809 965
user3 9 12809 965
user4 0 12809 965
I can’t figure out where did I go worng in my query.
Any suggestion to solve my problem?
Thank you for your help.
The reason why all the same values showed up was because there was no distinction between the
userstable in the outer query and theuserstable in the inner query. They both have the same alias. You must distinguish either the outeruserstable or the inneruserstable by assigning it with a different alias (such asu) so that the subquery knows which table to reference for the outer value:Having said that, it is highly inefficient to use subqueries like that as they would need to be executed for each row in your
userstable (we’re talking about entire tables needing to be joined and filtered as many times as there are users x2).Your query could be rewritten MUCH more efficiently using conditional aggregation:
Which basically says: SUM the credit/debit ONLY if the type is
xvalue, and you can SUM/COUNT/AVG/etc. on any condition you want just working with one table join.SQL-Fiddle Demo