MySql按内部连接和子查询的最高值排序

时间:2014-07-21 19:52:46

标签: mysql mysqli

我有一个查询,它有一个子查询,返回另一个表中的记录计数,我在订购此计数器的最大数量时遇到问题

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`

我想按总列排序而不能。 按总计排序不起作用,仅按ID

排序

1 个答案:

答案 0 :(得分:0)

您可以选择按数字顺序排列的列:

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?