Update SQLite table based on data in another table

◇◆丶佛笑我妖孽 提交于 2019-12-22 13:56:58

问题


I have two tables in SQLite which look like this

TABLE_X    
____________________
| id | C1 | C2 | C3 | C4 |
| 10 | 99 | 03 | 04 | 00 |
| 60 | 88 | 20 | 30 | 40 |


TABLE_Y
___________     
| id | C2 |
| 10 | 11 |
| 60 | 22 |

I am trying to write query to update records on Table X based on records in Table Y The condition for the updateis something like the following

update table_x
   set table_x.c1 = 100,
       table_x.c2 = table_y.c2
 where table_x.id = table_y.id

But when I try to do this I get an error message saying

NO such column: table_y.c2


回答1:


The deleted answer was correct about the cause of the error: a relation identifier must be introduced (e.g. with FROM/JOIN) in a query before it can be used.

While SQLite does not support UPDATE..JOIN (so there is no way to introduce the lookup relation directly), a dependent sub-query can be used to simulate the effect:

update table_x
   set c1 = 100,
       c2 = (select y.c2 from table_y as y
             where y.id = table_x.id)

Note that unlike a proper UPDATE..JOIN, if the sub-select fails to find a match then NULL will be assigned.

YMMV.



来源:https://stackoverflow.com/questions/19713678/update-sqlite-table-based-on-data-in-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!