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

r8uurelv  于 2023-08-02  发布在  Mysql
关注(0)|答案(3)|浏览(108)

我在帮一个朋友的网站,但我实际上被困在这一点上。
他的数据库是他自己创建的,他对数据库建模一无所知,所以我很难从中得到我想要的结果。
我得到了下面的查询,它有我需要的一切:

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低,这些行应该出现在鹰眼之前,如下所示:

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个,如果你需要完整的列表,只是让我知道。

chhkpiq4

chhkpiq41#

您只需要添加tabelaseriesbs.id ASC作为order by条件。这可能会打乱你的其他条件的顺序,虽然这取决于你把它放在哪里,但根据我如何解释你的查询,把这个作为你的最终条件应该保持你的其他相对顺序,并为你的id排序。

41zrol4v

41zrol4v2#

开始查询:

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 [...]

字符串
子查询将为每个nome找到最小的indice
然后可以在ORDER BY子句中使用min_indice

ORDER BY order_table.min_indice, [...]

t3irkdon

t3irkdon3#

试试这个

ORDER BY table.char DESC, table.id ASC

字符串

相关问题