有没有办法在MySQL中获得这个结果顺序?

时间:2017-07-28 19:02:07

标签: mysql sql-order-by

大家。

我在他的网站上帮助了一位朋友,但我实际上已经陷入了困境。

他的数据库是由他自己创建的,他不了解数据库建模,所以我很难从中得到我想要的结果。

我已经得到了以下任何我需要的查询:

SELECT * FROM tabelaseriesbs 
    LEFT JOIN tabelatextosbs ON tabelatextosbs.nome = tabelaseriesbs.nome and tabelaseriesbs.alter_ego = tabelatextosbs.alter_ego and tabelatextosbs.versao = tabelaseriesbs.versao
    LEFT JOIN tabelaformatosbs ON tabelaformatosbs.colecao = tabelaseriesbs.colecao,
        (SELECT distinct tabelaseriesbs.nome, tabelaseriesbs.alter_ego, tabelaseriesbs.versao FROM tabelaseriesbs
        LEFT JOIN tabelaformatosbs ON tabelaformatosbs.colecao = tabelaseriesbs.colecao,
            (SELECT tabelaseriesbs.nome, tabelaseriesbs.alter_ego, tabelaseriesbs.versao FROM tabelaseriesbs 
                WHERE 1=1 AND (tabelaseriesbs.colecao = 'Universo Marvel') AND (tabelaseriesbs.raridade = 'Comum')
            ) col 
        WHERE 1=1 AND (col.nome = tabelaseriesbs.nome) AND (col.alter_ego = tabelaseriesbs.alter_ego) 
                  AND (col.versao = tabelaseriesbs.versao) AND (tabelaformatosbs.formato >= 2) 
         ) form 
    WHERE 1=1 AND (tabelaseriesbs.alter_ego = form.alter_ego) 
              AND (tabelaseriesbs.nome = form.nome) 
              AND (tabelaseriesbs.versao = form.versao) 
              AND (tabelatextosbs.sitiada_afiliacoes = '0') 
    ORDER BY tabelatextosbs.nome ASC, tabelatextosbs.alter_ego ASC, tabelatextosbs.versao ASC, cast(tabelaseriesbs.indice AS SIGNED) ASC;

产生以下结果

indice  nome       series
2       Hawkeye    Universo Marvel
4       Hawkeye    Poderes Ocultos
6       Hawkeye    Iniciativa Vingadores
8       Hawkeye    Battle Box
10      Hawkeye    Guerra Civil
1       Mercenary  Universo Marvel
3       Mercenary  Ascensão e Queda
5       Mercenary  Ascensão e Queda - Deck

但是由于第一个雇佣兵的id低于第一个鹰眼的id,所以这些行必须出现在Hawkeye之前,如下:

indice  nome       series
1       Mercenary  Universo Marvel
3       Mercenary  Ascensão e Queda
5       Mercenary  Ascensão e Queda - Deck
2       Hawkeye    Universo Marvel
4       Hawkeye    Poderes Ocultos
6       Hawkeye    Iniciativa Vingadores
8       Hawkeye    Battle Box
10      Hawkeye    Guerra Civil

有办法吗?或者在获得结果后我是否必须在代码中执行此操作?此外,还有比3更多的字段,如果您需要完整列表,请告诉我。

3 个答案:

答案 0 :(得分:1)

您只需要按条件添加tabelaseriesbs.id ASC作为订单。这可能会因条件而中断您的其他订单,但取决于您放置它的位置,但根据我解释您的查询的方式,将此作为您的最终条件应该保留您的其他相关订单并订购您的ID。

答案 1 :(得分:0)

试试这个

ORDER BY table.char DESC, table.id ASC

答案 2 :(得分:0)

开始查询:

SELECT * 
FROM tabelaseriesbs
INNER JOIN (
    SELECT nome, MIN(cast(indice AS SIGNED)) as min_indice
    FROM tabelaseriesbs
    GROUP BY nome
) order_table USING (nome)
LEFT JOIN [...]

子查询将为每个indice找到最少的nome

然后您可以在ORDER BY子句中使用min_indice

ORDER BY order_table.min_indice, [...]