在sqlserver中更新一列数据和自动编号的问题!

tomelrg 2010-09-20 02:22:58
问题一:

有两张表
现在要更新t2中的file1字段,使 t2.file1的字段值 等于t1.id的值,其中t1和t2通过 t1.file2 和t2.file2相关联,t2的数据量要大于t1中的数据量,如果在t2中找不到对应的值,则不更新。
这个更新语句改怎么写?

t1 t2
id file2 file3 file1 file2
1 1 2 1 1
2 2 3 2 3
3 3 2 1 2
3 4


问题二:
要从别的表中选取数据创建如下的表(字段1和字段3的数据从别的表中来)

字段1 字段2 字段3 (字段1和字段2为表的主键)
a 1 s
a 2 d
a 3 s
a 4 d
b 1 s
b 2 d
b 3 s
b 4 s
b 5 d
b 6 d
c 1 a
c 2 s
c 3 a


现在的问题是 创建表时 如何让字段2根据字段1来自动编号?
...全文
243 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
tomelrg 2010-09-27
  • 打赏
  • 举报
回复
不好意思 过了个中秋 忘了结贴了
abuying 2010-09-20
  • 打赏
  • 举报
回复

-1
update t2
set file1 = t1.id
from t2 inner join t1
on t2.file2 = t1.file2
-2 使用row_number,rank通过partition by分区 排序可解决 但是在2005版本中

select col1,col2,col3 from
(select col1,rank() over(partition by col1 order by col1 asc) as col2,col3 form tb) as a
tomelrg 2010-09-20
  • 打赏
  • 举报
回复
2000下怎么做啊?
[Quote=引用 9 楼 baiying15 的回复:]

SQL code

;with aa as (
select 字段1,字段3,row_number() over (partition by 字段1 order by select 1 )as 字段2
from tb
)
select 字段1 字段2 字段3
from aa
[/Quote]
majiemiao 2010-09-20
  • 打赏
  • 举报
回复
UPDATE a SET file1=b.file1
FROM t2 a INNER JOIN t1 b
ON a.file2=b.file2
baiying15 2010-09-20
  • 打赏
  • 举报
回复

;with aa as (
select 字段1,字段3,row_number() over (partition by 字段1 order by select 1 )as 字段2
from tb
)
select 字段1 字段2 字段3
from aa
baiying15 2010-09-20
  • 打赏
  • 举报
回复
;with aa as (
select 字段1,字段3,row_number() over (partition by 字段1 order by select 1 )as 字段2
from tb
)
select 字段1 字段2 字段3
from aa
dawugui 2010-09-20
  • 打赏
  • 举报
回复
问题二比较麻烦,字段1 + 字段3 存在重复。
水族杰纶 2010-09-20
  • 打赏
  • 举报
回复
从别的表中选取数据的时候下功夫
2005 row_nubmer
2000可以根据ID列或者主键,唯一列等子查询处理
chuifengde 2010-09-20
  • 打赏
  • 举报
回复
1.UPDATE a SET file1=b.file1
FROM t2 a INNER JOIN t1 b
ON a.file2=b.file2

2.2000可以用变量更新
2008可以rownumber
baiying15 2010-09-20
  • 打赏
  • 举报
回复

update t2 set file1=t1.id
from t1,t2
where t2.file2=t1.file2
dawugui 2010-09-20
  • 打赏
  • 举报
回复
问题一:

update t2
set file1 = t1.id
from t2 , t1
where t2.file2 = t1.file2
喜-喜 2010-09-20
  • 打赏
  • 举报
回复
--1
update t2 set file1=t1.id
from t1,t2 where t2.file2=t1.file2

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧