删除数据库表中记录

来源:百度知道 编辑:UC知道 时间:2024/07/04 04:10:48
有一个表,没有唯一索引和主键,里边的记录可能有重复,我现在想把其中一个字段设置成主键,怎么删除里边重复的记录,比如表为A,我想设成主键的字段为ID,里边的记录可能如下:
ID I1 I2
1 x y
1 x z
1 d f
2 g l
3 h n
最后我想要
ID I1 I2
1
2
3
只要求ID字段唯一,I1,I2字段是取的哪一条记录的值都无所谓

delete from TableName t where t.rowid > (select min(rowid) from TableName c where c.id = t.id);

Oracle的。

可以做到。
如果是oracle
delete from table where rowid not in (select min(rowid) from table)
如果是其他的数据库
可以采用新建一个一样结构的表
然后
insert into newtable (id, 1, 2) select id, min(1), min(2) from table group by id

用临时表中转一下吧。
select id,l1,l2,identity(int,1,1) as nid
into #a
from a

truncate table a

insert into a(id,l1,l2)
select id,l1,l2
from #a
where nid in(select min(nid) from #a group by id)

select distinct t.id, max(t.l1), max(t.l2)
from a t
group by t.id
order by t.id

select id,min(l1) l1,min(l2) l2 from A group by id;

DELETE TEST
WHERE ROWID IN (
SELECT r_id
FROM (SELECT ROWID r_id, ID,
ROW_NUMBER () OVER (PARTITION BY ID ORDER BY ID)