mysql – SUM in SELECT with LEFT JOIN being multiplied with each other

Question:

I have 3 tables in MYSQL.

Account:

id  nome

1   caio
2   zé
3   marcelo

Followers (the account id, i.e. user caio has 2 followers):

idqual

1
1
2
2
2
3

Products (the account id, i.e. user caio has 3 products):

idqual
1
1
1
2
2
3

What I have to do is a query sorting by the number of products that each user has and the number of followers that each user has, then I have to list how many products and how many followers each user has, I thought it would be easy to do that, and I did so:

SELECT conta.id, conta.nome, count(produtos.idqual) as somaprodutos, count(seguidores.idqual) as somaseguidores FROM conta 
LEFT JOIN produtos ON conta.id = produtos.idqual
LEFT JOIN seguidores ON conta.id = seguidores.idqual
GROUP BY conta.id, conta.nome
ORDER BY SUM(somaprodutos) DESC,
SUM(somaseguidores) DESC

The error that occurs is that the value of sumfollowers and domaproducts is being the same, and this value is always their multiplication, example:

It is saying that user Caio has 6 followers and 6 products (2 followers * 3 products), what did I do wrong?

Answer:

See if it helps:

        SELECT conta.id,
               conta.nome, 
               (select count(*) from produto where produto.idqual = conta.id) QtdProdutos,
               (select count(*) from seguidores where seguidores.idqual = conta.id) QtdSeguidores

        FROM conta

        GROUP BY  conta.id,
                  conta.nome

        ORDER BY QtdProdutos,QtdSeguidores
Scroll to Top