Room DAO Order By ASC or DESC variable

帅比萌擦擦* 提交于 2021-02-07 04:54:40

问题


I'm trying to make a @Query function in my @Dao interface which has a boolean parameter, isAsc to determine the order:

@Query("SELECT * FROM Persons ORDER BY first_name (:isAsc ? ASC : DESC)")
List<Person> getPersonsAlphabetically(boolean isAsc);

Apparently this isn't allowed. Is there a work around here?

EDIT:

It seemed odd to use two queries (below) since the only difference is ASC and DESC:

@Query("SELECT * FROM Persons ORDER BY last_name ASC")
List<Person> getPersonsSortByAscLastName();

@Query("SELECT * FROM Persons ORDER BY last_name DESC")
List<Person> getPersonsSortByDescLastName();

回答1:


Use CASE Expression for SQLite to achieve this in Room DAO,

@Query("SELECT * FROM Persons ORDER BY 
        CASE WHEN :isAsc = 1 THEN first_name END ASC, 
        CASE WHEN :isAsc = 0 THEN first_name END DESC")
List<Person> getPersonsAlphabetically(boolean isAsc);



回答2:


Create two queries, one with ASC and one with DESC.

@Query("SELECT * FROM Persons ORDER BY last_name ASC")
List<Person> getPersonsSortByAscLastName();

@Query("SELECT * FROM Persons ORDER BY last_name DESC")
List<Person> getPersonsSortByDescLastName();



回答3:


Why don't you try something like this? I have not tested it.

@Query("SELECT * FROM Persons ORDER BY first_name :order")
List<Person> getPersonsAlphabetically(String order);

And the logic you suggested should go before you make the query.



来源:https://stackoverflow.com/questions/55297165/room-dao-order-by-asc-or-desc-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!