如何将 table 的选定结果插入 Android Room 的 DAO class 上的另一个 table

How to insert selected result from a table into another table on Android Room's DAO class

我一直在 Android Studio 上开发预算支出跟踪应用程序。 在这个特定的部分,我想要做的是将 table “budget_tracker_table” 的选定结果插入另一个 table “budget_tracker_table_alias”。 当我在 App Inspection 中执行它时,我编码的 SQL 没有任何问题,当我将完全相同的行放在 DAO class 中时,它显示错误,说“找不到方法 'value'”。这个问题有什么可能的解决方案吗? 谢谢。

@Insert("insert into budget_tracker_table_alias (date_alias, store_name_alias, product_name_alias, product_type_alias, price_alias, product_type_percentage) select date, store_name, product_name, product_type, price, count(*) * 100.0 / (select count(*) from budget_tracker_table where date >= '2022-4-22' and date <= '2022-4-23') as 'Percentage' from budget_tracker_table where date >= '2022-4-22' and date <= '2022-4-23' group by store_name;")
void insert(BudgetTrackerAlias budgetTrackerAlias);

房间的 @Insert 是一个方便的插入,它只需要一个对象(或对象列表),并且该对象是相应实体的 type/class 的对象。

您需要使用带有 SQL 的@Query 来插入,所以

@Query("insert into budget_tracker_table_alias (date_alias, store_name_alias, product_name_alias, product_type_alias, price_alias, product_type_percentage) select date, store_name, product_name, product_type, price, count(*) * 100.0 / (select count(*) from budget_tracker_table where date >= '2022-4-22' and date <= '2022-4-23') as 'Percentage' from budget_tracker_table where date >= '2022-4-22' and date <= '2022-4-23' group by store_name;")
void insert();

当然,这可能会受到限制,因为日期是硬编码的,如果您想传递日期,那么您可以:-

@Query("insert into budget_tracker_table_alias (date_alias, store_name_alias, product_name_alias, product_type_alias, price_alias, product_type_percentage) select date, store_name, product_name, product_type, price, count(*) * 100.0 / (select count(*) from budget_tracker_table where date >= :fromDate and date <= :toDate) as 'Percentage' from budget_tracker_table where date >= :formDate and date <= :toDate group by store_name;")
void insert(String fromDate,String toDate);

P.S。与 @Delete@Update 相同,即他们期望对象,但您可以使用 @Query 来利用 UPDATE/DELETE SQL