How to get row number in SQLite?

后端 未结 1 1042
梦毁少年i
梦毁少年i 2021-01-20 00:42

I\'ve read many articles regarding how to use a row number in SQLite but none of them gave me the answer I need. I know how to select row number using this query:

         


        
相关标签:
1条回答
  • 2021-01-20 01:10

    Your query contains an error: the alias "ja" is not defined.

    Try it like this:

    SELECT 
      ( SELECT COUNT(*) + 1 
        FROM "table" 
        WHERE title < t.title OR (title = t.title AND id<t.id)
      ) as rowIndex, 
      t.title 
    FROM "table" t 
    ORDER BY t.title;
    

    However, be aware that this sub-query construction will not scale well. For large datasets you might want to create a temp table and use ROWID instead (as discussed, for example, here).

    EDIT: Test with COLLATE NOCASE:

    CREATE TABLE "table" (id INTEGER, title TEXT COLLATE NOCASE);
    
    INSERT INTO "table" VALUES 
    (1, "Book A"), 
    (2, "Book b"), 
    (3, "Book C"), 
    (4, "Book B"), 
    (5, "Book a"); 
    

    The query yields:

    1|Book A
    2|Book a
    3|Book b
    4|Book B
    5|Book C
    

    EDIT:

    If you do not want to declare the column COLLATE NOCASE, you have to make sure that you use COLLATE in the ORDER BY part as well as in the subquery:

    SELECT 
      ( SELECT COUNT(*) + 1 
        FROM "table" 
        WHERE title < t.title COLLATE NOCASE OR (title = t.title COLLATE NOCASE  AND id<t.id)
      ) as rowIndex, 
      t.title 
    FROM "table" t 
    ORDER BY t.title COLLATE NOCASE;
    
    0 讨论(0)
提交回复
热议问题