例如,在 Android App 中,我想从本地 SQLite 数据库中,取所有未完成的任务,及已完成的任务的前50条。限制读取已完成条数是为了防止数据量过大,内存不可控。
Room 中的查询 SQL
在 DAO 代码中:
@Query("""
SELECT * FROM (
SELECT * FROM (SELECT * FROM todos WHERE done = 0)
UNION
SELECT * FROM (SELECT * FROM todos WHERE done = 1 ORDER BY id DESC LIMIT 50)
) ORDER BY done ASC, id DESC
""")
fun getTodos(): Flow<List<Todo>>
无效的 SQL 写法
无效 SQL 一:
@Query("""
SELECT * FROM todos WHERE done = 0 ORDER BY id DESC
UNION
SELECT * FROM todos WHERE done = 1 ORDER BY id DESC LIMIT 50
""")
fun getTodos(): Flow<List<Todo>>
Android Studio 编译时报错, Execution failed for task ':app:kaptDebugKotlin':
LIMIT, comma or semicolon expected, got 'UNION'
无效 SQL 二:
@Query("""
SELECT * FROM (SELECT * FROM todos WHERE done = 0 ORDER BY id DESC)
UNION
SELECT * FROM (SELECT * FROM todos WHERE done = 1 ORDER BY id DESC LIMIT 50)
""")
fun getTodos(): Flow<List<Todo>>
使用这个 SQL,返回的结果呈无序状态。待办事项无法排在已完成项的前面。
参考
- https://www.tutorialspoint.com/sqlite/sqlite_unions_clause.htm
微信关注我哦 👍
我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式