How to select a specific column from room database given a specific parameter in room query?

落花浮王杯 提交于 2020-02-06 04:31:27

问题


How can I do the following?

I want to select a specific column in my room query. This column will be specified by as a parameter in the query function.

Imagine my database looks like the following:

+----+---------+---------+---------+---------+
| ID | Column1 | Column2 | Column3 | Column4 |
+----+---------+---------+---------+---------+
| 1  | 13      | 45      | 77      | 12      |
+----+---------+---------+---------+---------+
| 2  | 5       | 34      | 67      | 7       |
+----+---------+---------+---------+---------+
| 3  | 8       | 33      | 69      | 12      |
+----+---------+---------+---------+---------+

I would like to be able to specify any of the columns and return the value in the specified column for all rows.

@Query("SELECT " + desiredSubcategory + " AS subcategoryValue FROM subcategory_table")
List<Subcategory> getSubcategory(String desiredSubcategory);
class Subcategory {
      Float subcategoryValue;

      public void setSubcategoryValue(Float subcategoryValue) {
            this.subcategoryValue = subcategoryValue;
      }

}

Edit 1: According to this post: Room: pass columns Name as parameter in DAO Method this feature is impossible to do. However, this was a year ago.


回答1:


You can do with Common Table Expression with CASE's like

@Query("WITH parms(c) AS (SELECT :columnName) " +
        "SELECT  COALESCE(" +
        "CASE " +
        "WHEN (SELECT c FROM parms) = 'column1' THEN column1 " +
        "WHEN (SELECT c FROM parms) = 'column2' THEN column2 " +
        "WHEN (SELECT c FROM parms) = 'column3' THEN column3 " +
        "WHEN (SELECT c FROM parms) = 'column4' THEN column4 " +
        "END" +
        ",0) AS subcategoryValue " +
        "FROM subcategory_table" +
        ";")
float[] getSubcategory(String columnName);

The Subcategory class not needed and is less efficient, but could use if wanted change float[] getSubcategory(String columnName); to List<Subcategory> getSubcategory(String columnName);




回答2:


Normal SQL would simply use

SELECT COLUMN1, COLUMN2, COLUMN3, COLUMN4 from <TABLE>

so probably something like

@Query("SELECT " + desiredSubcategory1 + " AS subcategoryValue1 + "," +
desiredSubcategory2 + " AS subcategoryValue2 + "," +
desiredSubcategory3 + " AS subcategoryValue3 + "," +
desiredSubcategory4 + " AS subcategoryValue4 + "," +
"FROM subcategory_table")
List<Subcategory> getSubcategory(String desiredSubcategory);


来源:https://stackoverflow.com/questions/59804148/how-to-select-a-specific-column-from-room-database-given-a-specific-parameter-in

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