求一个关于复合主键的Sql语句

云淡风清水蓝 2009-01-17 06:16:48
现在有一个表A,其中字段a1,a2
我想让a1,a2成为复合主键,所以想清除表中的冗余记录

例如表中有记录:
a1, a2 ...
AA01 1
AA01 2
AA01 3
AA02 1
AA02 1 *
AA03 1
AA03 2
AA03 3
那么我必须得先清除打星号的那一行(AA02 1...)数据,才能将a1,a2做成复合主键,请问该如何写这个SQL?

...全文
260 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wojiaochenglong 2009-01-17
  • 打赏
  • 举报
回复
五楼的方案应该可以
liulang406 2009-01-17
  • 打赏
  • 举报
回复
加个自增列ID,直接删
delete from A where id in
(SELECT max(id) as id FROM A group by a1,a2 having count(*)>1)
ks_reny 2009-01-17
  • 打赏
  • 举报
回复
先用distinct 去掉重複的記錄,再把這些記錄放入臨時表,接著清空原表,隨後從臨時表中把數據插入到原表.最後再設複合主鍵.
云淡风清水蓝 2009-01-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 wufeng4552 的回复:]
SQL codedeclare@tabletable(a1varchar(20),a2varchar(10))insertinto@tableselect'AA01',1unionallselect'AA01',2unionallselect'AA01',3unionallselect'AA02',1unionallselect'AA02',1unionallselect'AA03',1unionallselect'AA03',2unionallselect'AA03',3declare@iintset@i=0update@tableseta2=@i,@i=@i+1wherea1='AA02'select*from@tabledelete@tablewherea1='AA02'anda2=2select*from@table/*(8 行受影响)

(2 行受影响)
a1…
[/Quote]

对于a1,a2列,这里的假设是可能有很多重复对,比如说总共有1万条数据,我想找出其中的<a1,a2>重复的记录,然后把重复的记录删除。
云淡风清水蓝 2009-01-17
  • 打赏
  • 举报
回复
抱歉,可能我没有说清楚,星号‘*’不是数据表中的内容,是我标注该行用来说明的。

表中有两行相同的
AA02 1
AA02 1
因此我想清除类似这样的重复行。
水族杰纶 2009-01-17
  • 打赏
  • 举报
回复
declare @table table(a1 varchar(20),a2 varchar(10))
insert into @table
select 'AA01',1 union all
select 'AA01',2 union all
select 'AA01',3 union all
select 'AA02',1 union all
select 'AA02',1 union all
select 'AA03',1 union all
select 'AA03',2 union all
select 'AA03',3
declare @i int
set @i=0
update @table set a2=@i,@i=@i+1 where a1='AA02'
select * from @table
delete @table where a1='AA02' and a2=2
select * from @table
/*
(8 行受影响)

(2 行受影响)
a1 a2
-------------------- ----------
AA01 1
AA01 2
AA01 3
AA02 1
AA02 2
AA03 1
AA03 2
AA03 3

(8 行受影响)

(1 行受影响)

a1 a2
-------------------- ----------
AA01 1
AA01 2
AA01 3
AA02 1
AA03 1
AA03 2
AA03 3

(7 行受影响)

*/
nalnait 2009-01-17
  • 打赏
  • 举报
回复

declare @table table(a1 varchar(20),a2 varchar(10))
insert into @table
select 'AA01','1' union all
select 'AA01','2' union all
select 'AA01','3' union all
select 'AA02','1' union all
select 'AA02','1 *' union all
select 'AA03','1' union all
select 'AA03','2' union all
select 'AA03','3'

SELECT a1+a2,* FROM @table WHERE ISNUMERIC(a2)=1
------------result:
/*
AA011 AA01 1
AA012 AA01 2
AA013 AA01 3
AA021 AA02 1
AA031 AA03 1
AA032 AA03 2
AA033 AA03 3
*/

34,590

社区成员

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

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