Android Room从其他表获取字段

时间:2019-01-12 08:19:24

标签: android sql foreign-keys android-room

在我的应用程序中,我有两个表:操作和类别。

操作表

@Entity(tableName = "OperationsTable")
public class Operation
{
    @PrimaryKey (autoGenerate = true)
    private int OperationNumber;
    private int Year;
    private int Month;
    private int Day;
    private String Category;
    private float Amount;
}

类别表

public class Category implements Serializable
{
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "CategoryName")
    private String name;

    @ColumnInfo(name = "CategoryType")
    private String type;

    @ColumnInfo(name = "IconID")
    private int iconID;
}

直到现在,我一直在查询以返回Operation的子集:

@Query("SELECT Category as CategoryName, SUM(Amount) as OperationQuantity FROM OperationsTable WHERE Year = :year AND KindOfOperation = 'Gasto' AND Month = :month GROUP BY Category ORDER BY SUM(Amount) DESC")
LiveData<List<OperationSubset>> getCategorizedExpensesInMonth(Integer year, Integer month);

子集是这样:

public class OperationSubset
{
    @ColumnInfo(name = "CategoryName")
    public String name;

    @ColumnInfo(name = "OperationQuantity")
    public float quantity;
}

现在,我想返回相同的子集,但从Categories表中添加一个字段:

public class OperationSubsetDesired
{
    @ColumnInfo(name = "CategoryName")
    public String name;

    @ColumnInfo(name = "OperationQuantity")
    public float quantity;

    public float iconID <-- from Categories table
}

我知道我必须使用关系,但是我为此感到挣扎。

1 个答案:

答案 0 :(得分:0)

 @Query("SELECT Category as CategoryName, SUM(Amount) as OperationQuantity, Categories.IconID" +
            " FROM OperationsTable LEFT JOIN Categories ON OperationsTable.Category = Categories.CategoryName" +
            " WHERE Year = :year AND KindOfOperation = 'Gasto' AND Month = :month GROUP BY Category ORDER BY SUM(Amount) DESC")

应该是这样。如果您将使用关系注释,则您的对象结构将有所不同。 有关加入的更多信息,您可以在这里https://www.w3schools.com/sql/sql_join.asp