批量刪除表中的重複資料,僅保留一條不重複資料

2022-02-12 22:59:24 字數 1281 閱讀 5038

我們在sql資料中,經常遇到乙個表中有許多的重複資料,如何才能刪除那些重複的資料,僅保留一條不重複的資料呢?

一般情況我們會分四步來處理:

1

--原來的表結構:

2create

table

dict_xh3(

4 id int

notnull

,5 xh varchar(50) not

null6)

78--1.新建一張臨時表xinghao

9create

table

xinghao10(

11 id int

notnull

,12 xh varchar(50) not

null13)

14--

2.設定正確的索引,忽略重複資料。

15go

16--

csdn標準寫法

17if

exists (select name from

sys.indexes

18where name = n'

ad_xh_unique')

19drop

index ad_xh_unique on

xinghao;

20go

21--

在表xinghao列xh上 建立乙個唯一索引,忽略重複資料

22create

unique

index

ad_xh_unique

23on xinghao(xh) with ignore_dup_key on

[primary];

24go

2526

--3.將帶有重複資料的表複製到該臨時表中

27go

28insert

into xinghao select

*from

dict_xh

29--

4.刪除原重複表的所有資料,將臨時表中的資料複製到原重複表,刪除臨時表

30go

31--

刪除原表中資料

32delete

from

dict_xh

33--

複製臨時表中的資料到原表

34insert

into dict_xh select

*from

xinghao

35--

刪除臨時表

36drop

table xinghao

刪除表中重複資料

刪除表中重複資料 取出line fancy2表中fancy name相同的最小fancy id 寫進tmp表 create table tmp as select min fancy id as col1 from line fancy2 group by fancy name 刪除line fan...

刪除表中重複資料

如果重複資料很多,被刪掉的可能是大部分記錄,業務又允許的情況下,可以考慮重建表 create table newtable as select distinct from table rename table to oldtable rename newtable to table create i...

sql 刪除重複資料 保留乙個

方法1 1 建立乙個臨時表,選取需要的資料。2 清空原表。3 臨時表資料匯入到原表。4 刪除臨時表。mysql select from student id name 11 aa 12 aa 13 bb 14 bb 15 bb 16 cc 6 rows in set mysql create tem...