【发布时间】:2019-03-13 18:14:09
【问题描述】:
我正在尝试获取在机架中具有一定数量组件的组件类别。
查询
@Query("SELECT id, name, component_amount = " +
" (SELECT COUNT(component.id) as amount " +
" FROM component " +
" WHERE component.rack_id = :rackID AND component_cat.id = component_cat_id ) " +
"FROM component_cat")
LiveData<List<ComponentCat>> getRackComponentCategories(long rackID);
组件猫
public class ComponentCat
{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public long componentCatID;
@ColumnInfo(name = "name")
private String componentCatName;
@ColumnInfo(name = "component_amount")
private int amountOfComponents;
public ComponentCat(String componentCatName, int amountOfComponents) {
this.componentCatName = componentCatName;
this.amountOfComponents = amountOfComponents;
}
在 PHPMyAdmin 中测试它可以工作,但是将此 SQL 放在我的 Room 应用程序中,我收到以下错误:
error: The columns returned by the query does not have the fields [amountOfComponents] in com.mwb.digitalstorage.model.ComponentCat even though they are annotated as non-null or primitive. Columns returned by the query: [id,name,component_amount = (SELECT COUNT(component.id) as amount FROM component WHERE component.rack_id = :rackID AND component_cat.id = component_cat_id )]
在 Room 中,如何将变量 amountOfComponents 设置为 COUNT() 结果?
我试过了:
- 有一个 COUNT(component.id) 作为 component_amount,但这样不会给出正确的结果
- 在 MySQL 中重新创建表并执行相同的查询,结果确实正确
- 在字段中删除@NonNull,没有区别
-
分配component_amount.amount
@Query("SELECT id, name, component_amount.amount = " + " (SELECT COUNT(component.id) as amount " ...
这不会构建
【问题讨论】:
标签: android sql database android-room