Sort Mysql results using two tables

Asked

Viewed 141 times

3

is the following, I have two tables, a so-called topical and other comments(which has a foreign key from the topical table), I wanted to list the topics by sorting them by the amount of comments each. I broke my head and could not do, I appreciate the help from now on. Thanks!

  • 1

    Put your query there for us to help you

  • The answers worked perfectly! Thanks anyway!

  • I made a small change... to return 0 (zero) if you don’t have any comments. Now it’s better. Let me know if you need to improve on your appointment.

2 answers

4

Follow an example of a 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

3


Use the COUNT with the GROUP BY.

I don’t 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.