使用 SQLite 使用另一个 table 的值更新列?

Update column with value from another table using SQLite?

我有两个 SQLite 表。我想用 table2.

中的值更新 table1 中的列

Table1,table1 (id INTEGER AUTOINCREMENT, status TEXT, name TEXT);:

| id |  status   | name |
|----|-----------|------|
|  1 | pending   | xyz  |
|  2 | completed | abc  |

Table 2, table2 (status TEXT, name TEXT, trans_id INTEGER);:

| trans_id |  status   | name |
|----------|-----------|------|
|        1 | refunded  | cvb  |
|        2 | cancelled | asd  |

我想将状态和名称从表 2 更新到表 1,其中 table1.id = table2.trans_id。我有这个查询:

UPDATE table1 
SET status = (SELECT t2.status FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id) , 
name = (SELECT t2.name FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)
WHERE id IN (SELECT trans_id FROM table1 t1,table2 t2 WHERE t1.id = t2.trans_id)

它错误地填充了 table1。这是结果表 1

| id |  status  | name |
|----|----------|------|
|  1 | refunded | cvb  |
|  2 | refunded | cvb  |

我的要求是这样的:

| id |  status   | name |
|----|-----------|------|
|  1 | refunded  | cvb  |
|  2 | cancelled | asd  |

我的查询有什么问题?我怎样才能实现它?

我假设 t2.trans_iduniqprimary keytable2 中。如果不是,那么如果它 return 多个结果,那么更新查询将会崩溃。在这种情况下,您要么需要使用 WHERE 应用更多过滤器,要么在需要任何结果时使用 TOP 1

           UPDATE table1 
           SET status = (SELECT t2.status FROM table2 t2 WHERE t2.trans_id = id) , 
               name = (SELECT t2.name FROM table2 t2 WHERE t2.trans_id = id)
           WHERE id IN (SELECT trans_id FROM table2 t2 WHERE t2.trans_id= id)

如果table2中有id列,前面的回答就会失败。最好用全名 table1.id

UPDATE table1 
SET status = (SELECT t2.status FROM table2 t2 WHERE t2.trans_id = table1.id) , 
    name = (SELECT t2.name FROM table2 t2 WHERE t2.trans_id = table1.id)
WHERE id IN (SELECT trans_id FROM table2 t2 WHERE t2.trans_id= table1.id);