按此顺序根据主 ID 更新列

发布于 2024-11-26 15:29:15 字数 621 浏览 1 评论 0原文

这是测试代码。我希望更新 city_id,以便 city_id 必须与 select 语句中出现的该城市的第一个 id 匹配。例子。在这里,我希望 city_id [最后一列] 为 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) 

两个查询是如果这样就可以了。我显然有大量记录。创建临时表并将结果输出到文本文件也可以。在这种情况下,您将打印 id 和 city_id

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

enter image description here

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘过的浮云 2024-12-03 15:29:15

最好的方法是创建一个名为 cities 的新表,其中包含列 city_idcity_name。这称为规范化数据库,并降低问题的复杂性。

对于您的示例,您将拥有:

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

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
相权↑美人 2024-12-03 15:29:15

就像这样:

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

祝你好运!

Like this:

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

Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文