Copy SEVERAL Column Values from One table into Another Matching IDs - SQLite

怎甘沉沦 提交于 2020-01-25 08:04:03

问题


I'm elaborating on this question (Copy Column Value from One table into Another Matching IDs - SQLite) by adding an extra challenge.

The idea is to copy the value of several columns from one table to another when an id is matching. The aforementioned question addresses how to copy the content of one column when a matching id is found. Here the code as posted by @scaisEdge:

UPDATE t1 
SET value = (
    SELECT value 
    FROM t2 
    WHERE t1.ID = t2.ID)

But what if we want to update several columns from that same row where t1.ID = t2.ID? Of course one could run it several times once for each column to be updated, however, that's extraordinarily inefficient as I have to update millions of rows. I guess that the less amount of logical comparisons that the query has to do the faster it will be. Any other ways of optimizing this task are welcome, the IDs are unique, both tables have the same number of rows, and the exact same values of ID are found in both tables. So sorting the tables is not out of the question.


回答1:


If your version of SQLite is 3.15.0+ you can do it with Row Values:

update t1 set 
(col1, col2) = (
  select col1, col2 
  from t2 
  where t2.id = t1.id 
)

See the demo.



来源:https://stackoverflow.com/questions/57718515/copy-several-column-values-from-one-table-into-another-matching-ids-sqlite

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