Room DAO Order By ASC or DESC variable

前端 未结 3 1641
旧时难觅i
旧时难觅i 2021-02-18 18:08

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

@Q         


        
相关标签:
3条回答
  • 2021-02-18 18:30

    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();
    
    0 讨论(0)
  • 2021-02-18 18:31

    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.

    0 讨论(0)
  • 2021-02-18 18:41

    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);
    
    0 讨论(0)
提交回复
热议问题