Order by field with SQLite

前端 未结 1 753
有刺的猬
有刺的猬 2021-01-13 09:55

I\'m actually working on a Symfony project at work and we are using Lucene for our search engine. I was trying to use SQLite in-memory database for unit tests (we are using

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

    This is quite nasty and clunky, but it should work. Create a temporary table, and insert the ordered list of IDs, as returned by Lucene. Join the table containing the items to the table containing the list of ordered IDs:

    CREATE TABLE item (
        id INTEGER PRIMARY KEY ASC,
        thing TEXT);
    
    INSERT INTO item (thing) VALUES ("thing 1");
    INSERT INTO item (thing) VALUES ("thing 2");
    INSERT INTO item (thing) VALUES ("thing 3");
    
    CREATE TEMP TABLE ordered (
        id INTEGER PRIMARY KEY ASC,
        item_id INTEGER);
    
    INSERT INTO ordered (item_id) VALUES (2);
    INSERT INTO ordered (item_id) VALUES (3);
    INSERT INTO ordered (item_id) VALUES (1);
    
    SELECT item.thing
    FROM item
    JOIN ordered
    ON ordered.item_id = item.id
    ORDER BY ordered.id;
    

    Output:

    thing 2
    thing 3
    thing 1
    

    Yes, it's the sort of SQL that will make people shudder, but I don't know of a SQLite equivalent for ORDER BY FIELD.

    0 讨论(0)
提交回复
热议问题