【问题标题】:Unable to set count value to column无法将计数值设置为列
【发布时间】: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


    【解决方案1】:

    Room 不支持为您的列指定别名。

    您的错误消息指出:

    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 )
    

    这意味着它将整个查询解释为一列。

    尝试将您的查询更改为以下内容:

    @Query("SELECT id, name, " +
            "       (SELECT COUNT(component.id) as amount " +
            "        FROM component " +
            "        WHERE component.rack_id = :rackID AND component_cat.id = component_cat_id ) as component_amount " +
            "FROM component_cat")
    LiveData<List<ComponentCat>> getRackComponentCategories(long rackID);
    

    【讨论】:

    • “这意味着它将整个查询解释为一列”这是我的目标,即分配给该列的查询结果。它适用于 PHPMyAdmin,但不适用于 Room。您的答案在 Room 中确实有效。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2019-05-03
    • 2022-01-06
    相关资源
    最近更新 更多