SQL: How to self-reference a column in update statements?

送分小仙女□ 提交于 2020-01-02 05:46:27

问题


I have two tables with these columns:

Users: user, class, grade, location.

Classes: class, location

The class column of the Users table references the same colmn in Classes table.

I want to update all rows in the Users table such that each row of the Users table's "location" column is equal to the location of the class.

So i have a row with values: Mike, Math, A+, New York

And the corresponding row in Classes table for Math is: Math, Chicago

I want the user table's row to become Mike, Math, A+, Chicago.

Thanks


回答1:


update users a
    set a.location =
     (select b.location 
      from classes b
      where b.class = a.class) 



回答2:


update
  users
set
  users.location = classes.location
from
  classes
where
  classes.class = users.class



回答3:


How about this:

UPDATE U 
SET U.Location = C.Location
FROM Users AS U
INNER JOIN Classes AS C ON C.Class = U.Class
                AND C.Location != U.Location
 ;


来源:https://stackoverflow.com/questions/8217721/sql-how-to-self-reference-a-column-in-update-statements

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