How to sort MySQL results with letters first, symbols last?

前端 未结 4 1731
盖世英雄少女心
盖世英雄少女心 2020-12-19 13:20

Long-time reader, first-time poster here.

I\'m trying to figure out how to sort a list of artists for a music app I\'m writing.

To help understand the databa

相关标签:
4条回答
  • 2020-12-19 14:01
    ORDER BY ASCII(SUBSTR(artist, 1, 1)) NOT BETWEEN 65 AND 122, artist
    

    This will order all artists that start with an alphabetical character before non alphabetical.

    Note that because of how ascii works [ \ ] & _ ` will be considered alphabetical. If this matters you can split it into two boolean expressions to do the upper and lower case letters separately.

    Or maybe:

    ORDER BY ASCII(UPPER(SUBSTR(artist, 1, 1))) NOT BETWEEN 65 AND 90, artist
    

    Be aware that this will only work for ascii characters. Letters that are part of other character sets won't be recognized as such.

    0 讨论(0)
  • 2020-12-19 14:08

    You can add an extra ORDER BY clause that puts the items that start with a non-alphabetic character last, like so:

        SELECT artist
          FROM songs
      ORDER BY artist REGEXP '^[^A-Za-z]' ASC, artist
    

    This should move every artist that doesn't start with A-Z or a-z to the end of your ordering.

    0 讨论(0)
  • 2020-12-19 14:10

    This will put all the artists who's names begin with a letter in a-z before those that don't:

    SELECT DISTINCT artist
    FROM songs
    ORDER BY artist REGEXP '^[a-z]' DESC, artist
    

    See it working online: sqlfiddle


    But you might prefer to store a second column with the simplified name so that you can put them in an order that makes more sense:

    artists
    
    artist            | simplified_name
    ------------------------------------
    &i                | i
    +NURSE            | nurse
    2007excalibur2007 | excalibur
    

    The values for simplified_name cannot be easily generated in MySQL, so you may want to use a general purpose programming language to pull out all the artists, transform them to simplified names, then populate the database with the results.

    Once this is done, you can use this query:

    SELECT DISTINCT artist
    FROM artists
    ORDER BY simplified_name
    
    0 讨论(0)
  • 2020-12-19 14:14

    if you want sort by symbol first

    • ★★★ Symbol ★★★
    • 101 Hair Care
    • Abc
    • Def

    then use below query

    ORDER BY artist REGEXP '^[^A-Za-z0-9]' DESC, artist ASC
    
    0 讨论(0)
提交回复
热议问题