【发布时间】:2020-10-14 21:22:58
【问题描述】:
我有一个用户实体和一个记录实体。我想要一个列表,显示所有用户及其按记录日期过滤的记录列表。但是,我无法根据条件过滤结果。
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
@Entity(tableName = "user_table")
public class User {
@PrimaryKey public long id;
public String name;
}
@Entity(tableName = "record_table")
public class Record {
@PrimaryKey @ColumnInfo(name = "record_id")public long recordId;
@ColumnInfo(name = "user_id") public long userId;
public String date;
@ColumnInfo(name = "action")
public String action;
}
public class UserWithRecords {
@Embedded
protected User user;
@Relation(
parentColumn = "id",
entity = Record.class,
entityColumn = "user_id"
)
protected List<Record> records;
}
这是我尝试过的所有查询:
//in Dao
//first try:
@Transaction
@Query("SELECT * FROM user_table LEFT JOIN record_table ON id = user_id WHERE date=:date")
public LiveData<List<UserWithRecords>> getDailyRecord(String date);
//second try:
@Transaction
@Query("SELECT * FROM user_table LEFT JOIN (SELECT * FROM record_table WHERE date=:date) ON id = user_id")
public LiveData<List<UserWithRecords>> getDailyRecord(String date);
//third try:
@Transaction
@Query("SELECT * FROM user_table INNER JOIN record_table ON id = user_id WHERE date=:date")
public LiveData<List<UserWithRecords>> getDailyRecord(String date);
<User> <Record>
id | name record_id | user_id | action | date
------------ ----------------------------------------
1 | Alice 1 | 1 | walk |2020-10-05
2 | Ben 2 | 1 | jog |2020-10-05
3 | Chris 3 | 2 | bike |2020-10-05
4 | 1 | walk |2020-10-14
5 | 2 | jog |2020-10-14
filtering by 2020-10-05 and get results with all queries:
id | name | record_id | action | date
----------------------------------
1 | Alice| 1 | walk | 2020-10-05
1 | Alice| 2 | jog | 2020-10-05
1 | Alice| 4 | walk | 2020-10-14
2 | Ben | 3 | bike | 2020-10-05
2 | Ben | 5 | jog | 2020-10-14
3 | Chris|------------------------------------->3rd query don't have this row
我怎样才能得到这样的东西?是否可以通过一个查询来完成?
id | name | record_id | action | date
-------------------------------------------
1 | Alice| 1 | walk | 2020-10-05
1 | Alice| 2 | jog | 2020-10-05
2 | Ben | 3 | bike | 2020-10-05
【问题讨论】:
标签: android android-sqlite android-room