Sort Mysql results using two tables

3

This is the following, I have two tables, one called topic and another comments (which has a foreign key of the table topics), I wanted to list the topics by ordering them by the amount of comments from each. I broke my head and could not do it, thank you for the help right away. Thanks!

    
asked by anonymous 12.01.2017 / 14:43

2 answers

3

Use COUNT with GROUP BY .

I do not know your structure, but that's what you have to do.

SELECT
    IFNULL(COUNT(COMENTARIOS.ID), 0) AS QUANTIDADE_COMENTARIOS
FROM
    COMENTARIOS
GROUP BY
    ID_TOPICO
ORDER BY
    QUANTIDADE_COMENTARIOS
    
12.01.2017 / 14:44
4

Here is an example query:

SELECT 
    t.NOME_TOPICO
    , count(c.id) qtd_comentarios

FROM TABELA_TOPICOS as t
left join TABELA_COMENTARIOS as c on c.fk_uf = t.id

group by t.id

order by count(t.id) desc
    
12.01.2017 / 14:49