哪位大哥救命啊!请问一个删除语句应该怎么写!!在线~~
有以下一张表tabla1,这张表id 是自增列,对应另外一张主表。
本来一个parentID对应只会有3个No的值,分别是1,2,3 三条记录
由于误操作的原因,现在一个parentID对应了多个重复的No 1,2,3有的重复了10几次
比如说parentID 1的数据是正常的,2不正常应该把ID 7,8,9的记录删除
比如说parentID 3 因该把对应的No 13,14,15删除。
应为有上万条数据,手工删除不太现实了,我想通过语句来删除
哪位大哥能帮个忙?
ID parentID No data1 data2 data3 data4
1 1 1 2 2 2 2
2 1 2 2 2 2 2
3 1 3 2 2 2 2
4 2 1 2 2 2 2
5 2 2 2 2 2 2
6 2 3 2 2 2 2
7 2 1 2 2 2 2
8 2 2 2 2 2 2
9 2 3 2 2 2 2
10 3 1 2 2 2 2
11 3 2 2 2 2 2
12 3 3 2 2 2 2
13 3 1 2 2 2 2
14 3 2 2 2 2 2
15 3 3 2 2 2 2
16 4 1 2 2 2 2
17 4 2 2 2 2 2
18 4 3 2 2 2 2
19 5 1 2 2 2 2
20 5 2 2 2 2 2
21 5 3 2 2 2 2
22 5 1 2 2 2 2
23 5 2 2 2 2 2
24 5 1 2 2 2 2
25 5 2 2 2 2 2
26 5 3 2 2 2 2
27 5 1 2 2 2 2
28 5 2 2 2 2 2
29 5 3 2 2 2 2
[解决办法]
ID parentID No data1 data2 data3 data4
1 1 1 2 2 2 2
2 1 2 2 2 2 2
===========>
delete a from tb a
where exists(select 1 from tb where parentid=a.parentid and no=a.no and id <a.id)
[解决办法]
delete a
from tablename a
where exists (
select 1 from tablename
where parentID=a.parentID
and No=a.No
and id <a.id
)
--上面删除语句应该没有问题,但是保险起见,建议先用一下语句查询,看是不是你需要删除的记录,再执行上面语句
select *
from tablename a
where exists (
select 1 from tablename
where parentID=a.parentID
and No=a.No
and id <a.id
)
[解决办法]
create table a(
ID int identity,
parentID int ,
No int
)
insert a select 1 , 1
union all select 1 , 2
union all select 1 , 3
union all select 2 , 1
union all select 2 , 2
union all select 2 , 3
union all select 2 , 1
union all select 2 , 2
union all select 2 , 3
delete from a where id not in(
select min(id) from a group by parentid,no )
select * from a
drop table a
[解决办法]
result:
111
212
313
421
522
623