SQL: How to self-reference a column in update stat

2019-05-06 08:56发布

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

标签: sql sybase
3条回答
老娘就宠你
2楼-- · 2019-05-06 09:20
update users a
    set a.location =
     (select b.location 
      from classes b
      where b.class = a.class) 
查看更多
老娘就宠你
3楼-- · 2019-05-06 09:29
update
  users
set
  users.location = classes.location
from
  classes
where
  classes.class = users.class
查看更多
做个烂人
4楼-- · 2019-05-06 09:31

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
 ;
查看更多
登录 后发表回答