问题
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