ORDER BY alphanumeric characters only in SQLite

后端 未结 5 1156
再見小時候
再見小時候 2021-02-05 15:24

I am sorting songs in SQLite (on Android). I want to order them:

  1. Case-insensitive
  2. With leading-digits at the end, by integer value.
  3. Without punct
5条回答
  •  孤城傲影
    2021-02-05 15:38

    In my opinion, the highest performance approach is to create a trigger to fill a new field named sort_key. You will need a primary key.

    CREATE TABLE songs (n INTEGER, name TEXT, 
                        sort_key TEXT, 
                        ID INTEGER PRIMARY KEY AUTOINCREMENT);
    
    CREATE TRIGGER songs_key_trigger
        AFTER INSERT ON songs FOR EACH ROW
        BEGIN n
            Declare @sort_key as varchar(255)
            -- calculate and call here your slugify function
            -- to fill sort_key from 'new.n' and 'new.name'
            UPDATE songs 
              SET sort_key = @sort_key
              WHERE ID = new.ID;
        END
    

    Realize that this approach is index friendly, you can create an index over new column to avoid table full scan operations.

提交回复
热议问题