SQL Query to Update One Column Based on Data from Another

巧了我就是萌 提交于 2019-12-12 20:26:57

问题


I need to update a table column in one table with data from another based on whether a specific id matches.

Basically, I have the following schema:

TABLE accounts FIELD old_user_id

TABLE users FIELD old_user_id FIELD new_user_id

I need to loop through all old_user_id's in the accounts table checking them against the old_user_id field in the users table, and then take the new_user_id value in the users table and replace the old_user_id value in the accounts table.

Seems like a simple thing to do but as my SQL is not amazing I'm struggling with working this out.


回答1:


Try This:

          UPDATE A 
          SET
                 A.old_user_id = U.new_user_id
          FROM Accounts A
          JOIN   Users U
          ON A.old_user_id = U.old_user_id


来源:https://stackoverflow.com/questions/17860465/sql-query-to-update-one-column-based-on-data-from-another

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