简体   繁体   中英

MySql sort by highest value with inner join and subquery

I have a query that has a sub query that returns a count of records from another table, I'm having trouble ordernar the largest number of this counter

SELECT respostas.id,
       respostas.cmm,
       respostas.topico,
       respostas.usuario,
       respostas.resposta,
       perfis.nome,
       perfis.sobrenome,
       respostas.datahora,
       (
           SELECT count(id) 
           FROM likes 
           WHERE respostas.id = resposta
       ) AS total
FROM respostas
INNER JOIN perfis ON respostas.usuario = perfis.id
INNER JOIN likes ON respostas.topico = likes.topico
WHERE respostas.cmm = 28
        AND respostas.topico = 38
ORDER BY respostas.id ASC, total ASC
                LIMIT 0,20`enter code here`

I want to sort by the total column and can not. Sorting by total does not work, only ordered by id

You can choose which column to order by numerically:

SELECT           
       (
           SELECT count(id) 
           FROM likes 
           WHERE respostas.id = resposta
       ) AS total,
       respostas.id,
       respostas.cmm,
       respostas.topico,
       respostas.usuario,
       respostas.resposta,
       perfis.nome,
       perfis.sobrenome,
       respostas.datahora
FROM respostas
INNER JOIN perfis ON respostas.usuario = perfis.id
INNER JOIN likes ON respostas.topico = likes.topico
WHERE respostas.cmm = 28
        AND respostas.topico = 38
ORDER BY 1, respostas.id
                LIMIT 0,20

What is the purpose of Order By 1 in SQL select statement?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM