Android Room按别名排序

时间:2018-07-02 21:34:03

标签: android

我想根据我创建的自定义别名对数据集进行排序。我尝试过,但是会导致语法错误。我在做什么错了?

代码:

@Query("SELECT a/b as ratio " +
        "FROM dataset " +
        "where my_status = :myStatus " +
        "order by ratio ASC")

找不到按比例排序的比率。

1 个答案:

答案 0 :(得分:1)

问题在于,Room在编译时会根据您的实体生成SQL查询。因此,Room只能识别您实体中指定的列名。

例如,如果您有实体Employee

@Entity(tableName = "employee_table")
public class Employee {
    private String firstName;
    private String lastName;
    private double monthlySalary;
}

您要计算年薪或日薪或其他方式,则可以在Employeeprivate double mathResult)中添加一列,然后将其用作别名:

@Dao
public interface EmployeeDao {
    @Query("select firstName, lastName, monthlySalary, monthlySalary*12 as mathResult from user_table order by mathResult asc")
    LiveData<List<Employee>> getUsers();    
}