SQLite:ORDER BY已加入的列

时间:2016-09-08 13:29:13

标签: java join sqlite sql-order-by

我有这个简单的要求:

SELECT *
FROM categories 
LEFT OUTER JOIN items ON categories.id = items.category_id 
ORDER BY items.category_id, items.name;

问题是结果是在 items.id 之后订购的,而不是两个指定的列。

如果我替换为:

ORDER BY categories.id, items.name;

效果很好,但它不使用我的索引:

CREATE INDEX items_index ON items(category_id, name);

我该如何妥善解决?谢谢。

编辑:以下是我创建2个表的方法:

// Categories
db.execSQL("CREATE TABLE categories (" +
            "id INTEGER PRIMARY KEY, " +
            "parent_id INTEGER , " +
            "resource_name TEXT, " +
            "FOREIGN KEY(parent_id) REFERENCES categories(id) ON UPDATE CASCADE ON DELETE CASCADE);");

db.execSQL("CREATE INDEX categories_index ON categories(parent_id);");

// Items
db.execSQL("CREATE TABLE items (" +
            "id INTEGER PRIMARY KEY, " +
            "category_id INTEGER , " +
            "name TEXT, " +
            "price REAL, " +
            "FOREIGN KEY(category_id) REFERENCES categories(id) ON UPDATE CASCADE ON DELETE CASCADE);");

db.execSQL("CREATE INDEX items_index ON items(category_id, name);");

我如何插入类别:

    ContentValues values = new ContentValues();
    values.put("id", category.getId());
    values.put("parent_id", category.getParentId());
    values.put("resource_name", category.getResourceName());

    db.insert("categories", null, values);

项目:

    ContentValues values = new ContentValues();
    values.put("category_id", item.getCategoryId());
    values.put("name", item.getName());
    values.put("price", item.getPrice());

    long id = db.insert("items", null, values);

0 个答案:

没有答案