android - sqlite首先按WHERE排序

标签 android sql sqlite

我正在尝试使用带有查询的 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 1type 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
  • 请注意以上内容有效地复制了您的代码

结果会是:-

  1. 原始解决方案

enter image description here

  1. 正确使用NOT IN

enter image description here

  1. 中保留分号

enter image description here

关于android - sqlite首先按WHERE排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682978/

相关文章:

安装过程中的 Android 错误 961

mysql - SQL SELECT 请求使用 count(*) 和多个 GROUP BY

sql - 如何在Django中更新M2M字段

sql - 如何从子查询返回两个字段

php - 使用 laravel dusk 进行登录测试

Python - mysqlDB,sqlite 结果作为字典

android - Android项目中的第二个Maven存储库

java.lang.UnsatisfiedLinkError : Native method not found in Android 错误

android - java.lang.NoClassDefFoundError : java. util.Objects[]

python - 如何为整个 Tornado Web 应用程序建立与 SQLite 数据库的一个连接?