简体   繁体   中英

Update a column based on the primary id in this order

Here is the test code. I would like the city_id to be updated such that the city_id must must match the first id of that city that appears in select statement. Example. Here I would like the city_id [last column] to be 1,1,3,3

在此处输入图片说明

create table student2 (id int not null primary key  identity,
city_name varchar(25),
student_name varchar(25),
city_id int  null)


insert into student2 values('Boston','Nome',null) 
insert into student2 values('Boston','Tiger',null) 
insert into student2 values('Miami','Andy',null) 
insert into student2 values('Miami','Moran',null) 

Two query's are fine if that does the job. I have obviously large number of records. Creating temporary table and outputting the result to text file is fine too. In that case you would print id and city_id

The best approach is to create a new table called cities , that contains columns city_id and city_name . This is called normalizing the database, and reduces the complexity of your problem.

For your example, you would have:

id |city_id |student_name
1  |1       |Nome
2  |1       |Tiger
3  |2       |Andy
4  |2       |Moran

city_id |city_name
1       |Boston
2       |Miami

Like this:

update student2
set city_id =
    (select min(id) from student2 s where s.city_name = student2.city_name)

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM