I have two tables on MySQL, with this structure:
Users:
id | name
Accounts:
id | userid | amount
I need a query to get the total accounts for each user, with the user name in the result too. Is there a way to achieve this? I’ve tried subqueries in the from clause, and I don’t know how to use a join to achieve this, but I have my doubts if that may be the solution… Any ideas?
Here’s sample data and an example output I’m pretending to get:
Users
1 | 'John'
2 | 'Peter'
Accounts
1 | 1 | 1000
2 | 1 | 2000
3 | 2 | 1500
query:
'John' | 2 <- there are 2 accounts for user 'John'
'Peter' | 1 <- there is only 1 account for user 'Peter'
Also, what if I like to have more summary data on my results? say… the total amounts. For example:
another query:
'John' | 2 | 3000 <- 2 accounts for John, which sums 3000
'Peter' | 1 | 1500 <- 1 account for Peter, which sums 1500
Here’s a query to get the user’s name and the count of their accounts:
To get a sum of the amount column, you can do something like: