房更新多个字段

问题描述 投票:1回答:1

我想更新从table 1一些领域是一样的来自另一个table(甚至是子查询)的值。问题是,我得到一个compilation errorDAO更新查询时,有超过10场。

你可以看到下面的代码(重写以通用):

@Query("UPDATE table1 " +
     " SET (field1, field2) = " +
     " (SELECT SUM(table2.foreign_field1) as summaryForeign_field1, table2.foreign_field2 " +
     " FROM table2 " +
     " WHERE   table1.id = table2.id " + 
     " GROUP BY table2.foreign_field2 ) ")
void setFieldsInTable1();

我查了一下,在SQLite Update Query Ref票据查询和我曾尝试在DB Browser代码为SQLite它工作正常。

任何帮助将不胜感激。

android sqlite dao android-room android-architecture-components
1个回答
1
投票

你忘了上线4 +

如果这仅仅是一个复制/过去的错误,那么就必须有一些错误,你当你试图使它通用的提问删除原始查询。

这应该工作,这里是一个工作示例:

Online example

代码:

BEGIN TRANSACTION;

/* Create tables */
CREATE TABLE table1(
    id integer PRIMARY KEY,
    field1 text,
    field2 text
);

CREATE TABLE table2(
    id integer PRIMARY KEY,
    field1 text,
    foreign_field1 integer,
    FOREIGN KEY(foreign_field1) REFERENCES table1(id)
);

/* Create few records */
INSERT INTO table1 VALUES(1,'Tom', 'French');
INSERT INTO table1 VALUES(2,'Lucy', 'American');
INSERT INTO table1 VALUES(3,'Frank', 'English');
INSERT INTO table1 VALUES(4,'Jane', 'Polish');
INSERT INTO table1 VALUES(5,'Robert', 'French');

INSERT INTO table2 VALUES(1,'Monday', 3);
INSERT INTO table2 VALUES(2,'Wednesday', 5);
INSERT INTO table2 VALUES(3,'Friday', 1);
INSERT INTO table2 VALUES(4,'Tuesday', 4);
INSERT INTO table2 VALUES(5,'Monday', 1);

COMMIT;

/* Display records from the table1 */
SELECT * FROM table1;

/* Update records from table1 */
UPDATE table1 
SET (field1, field2) = (
    SELECT
        SUM(table2.foreign_field1) as summaryForeign_field1,
        table2.field1 
    FROM table2 
    WHERE table1.id = table2.id 
    GROUP BY table2.field1
);

/* Check that the update has been executed correctly */
SELECT * FROM table1;

因此,也许尝试建立一个在线小例子,更接近原始查询。

编辑:OK按你的意见我已经测试并能重现该问题在我的项目,它确实不编译,错误是:

错误:在输入端没有可行的替代 '更新测试SET(名字,' 外来的输入 ')' 期待{, ';', '', '=', '*', '+', ' - ',“|| ”, '/', '%', '<<', '>>', '&', '|', '<', '<=', '>', '> =', '==' , '!=', '<>',...}

不幸的是,我认为这是一个房间的限制。也许你能问题提交给谷歌获得更多这方面的信息。

同时,您可以用RawQuery尝试(如文档说,它必须返回一个非void类型,但你可以返回例如假的字符串或空POJO):

@RawQuery
String setFieldsInTable1(SupportSQLiteQuery query);

然后使用它是这样的:

SimpleSQLiteQuery query = new SimpleSQLiteQuery("UPDATE table1 SET ...");
yourDao.setFieldsInTable1(query);

另一种方法是只需用2子查询这样走:

UPDATE table1
SET field1 = (
    SELECT SUM(table2.foreign_field1)
    FROM table2
    WHERE table1.id = table2.id
    GROUP BY table2.foreign_field2
),
field2 = (
    SELECT table2.foreign_field2
    FROM table2
    WHERE table1.id = table2.id
);

还取决于应用程序的工作流程,你可以修改你的实体在你的代码,然后使用Update界面更新:

@Update
void update(Table1Entity... table1Entities);
© www.soinside.com 2019 - 2024. All rights reserved.