2
I have two tables:
comentarios
---id
---comentario
---usuario
---supermercado
---avaliacao
supermercado
---id
---nome
---endereco
---admin
I want to take the average of ratings from each supermarket and get the 3 supermarkets with the highest average.
Example:
Supermercado01 in the table reviews have reviews:
4, 5, 3, 5 (média então é 4.25)
Supermercado02 in the table reviews have reviews:
1, 1, 1, 1 (média então é 1)
Supermercado03 in the table reviews have reviews:
4, 3, 3, 4 (média então é 3.5)
Supermercado04 in the table reviews have reviews:
1, 5, 2, 2 (média então é 2.5)
SQL should then return me the records of Supermercado01, Supermercado03 and Supermercado04. Could it be done in one SQL? I didn’t post any because the ones I tried were quite flawed, and I was also trying to get the result in PHP, but the performance got rough.
The best attempt was:
SELECT supermercados.nome, AVG(comentarios.avaliacao) as avaliacao
FROM supermercados, comentarios
WHERE 
supermercados.id = comentarios.supermercado ORDER BY avaliacao
						
Solved the case, what would be the effect of
GROUP BY? I can’t remember how it’s used.– Leonardo
Group by group by field(s) reported. There the aggregation functions (AVG, SUM, COUNT, etc.) are relived in the set of records where the reported fields are equal. In this case for all supermarkets of the same name.
– Nelson Teixeira