我正在尝试使用带有查询的 sqlite 对我的 android 应用程序中的一些数据进行排序
cursor c = db.query(TABLE_NAME, null, DRILL_TYPE + " IN ('type 1', 'type 2');", null, null, null, SIZE + " ASC", null);
我希望结果按大小排序,无论钻头是类型 1 还是类型 2,但我对所有类型 1 进行了排序,然后对所有类型 2 进行了排序。导致此结果的查询有什么问题?
expected:
type 1 1
type 2 2
type 1 3
type 2 4
type 1 5
type 2 6
actual result:
type 1 1
type 1 3
type 1 5
type 2 2
type 2 4
type 2 6
编辑,在回答原始问题后:-
删除订单部分末尾的分号修复了我使用 IN 时的问题,但不是我使用 NOT IN 时的问题
最佳答案
我认为问题可能是由于 IN 子句末尾的分号 ;
引起的。这将有效地标记 SQL 的结束,并因此导致 ORDER 子句被忽略/省略。
那就是尝试:-
cursor c = db.query(TABLE_NAME, null, DRILL_TYPE + " IN ('type 1', 'type 2')", null, null, null, SIZE + " ASC", null);
关于:-
removing the semicolon at the end of the order part fixed things when I use IN, but not when I use NOT IN
使用
cursor c = db.query(TABLE_NAME, null, DRILL_TYPE + " NOT IN ('type 1', 'type 2')", null, null, null, SIZE + " ASC", null);
将对没有type 1 或type 2 的行进行排序,正确地考虑以下内容(它复制了您的情况,但有额外的数据来显示 NOT在结果中):-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (drill_type TEXT, size INTEGER);
INSERT INTO mytable VALUES
('type 2',4),('type 1',5),('type 2',6),
('type 1',1),('type 2',2),('type 1',3),
('type 4',14),('type 3',15),('type 4',16),
('type 3',11),('type 4',12),('type 3',13)
;
SELECT * FROM mytable WHERE drill_type IN ('type 1','type 2') ORDER BY size ASC;
SELECT * FROM mytable WHERE drill_type NOT IN ('type 1','type 2') ORDER BY size ASC;
SELECT * FROM mytable WHERE drill_type NOT IN ('type 1','type 2'); ORDER BY size ASC; -- will not sort as expected
- 请注意以上内容有效地复制了您的代码
结果会是:-
- 原始解决方案
- 正确使用NOT IN
- 在 中保留分号
关于android - sqlite首先按WHERE排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682978/