当前位置:网站首页>sqlserver删除重复数据
sqlserver删除重复数据
2022-08-04 12:29:00 【lyk_dtf】
前言
老是有些项目忘记加唯一索引,如果项目正常运行倒也没事,但是一旦高并发或者服务器带宽波动,极可能出现重复数据,需要手动删除一下
最主要的还是别懒!索引一定要加,索引能将查询速度直接提高100倍
1、表结构
CREATE TABLE [dbo].[met_treasure_hunt_box_rec](
[rec_id] [int] IDENTITY(1,1) NOT NULL,
[userCode] [nvarchar](20) NULL,
[box_type] [int] NULL
)
userCode,box_type两个字段需要加联合唯一索引,语法如下:
@>_<当初加上也没下面什么事了,
alter table 表名 add unique index 索引名(字段1,字段2,字段3)
2、删除重复数据
大概的意思:
通过userCode、box_type 进行分组,查询分组中数量大于2的记录的主键id,每次只取每个分组中的第一条,得到一个id数组,然后delete in 删除
这个sql每执行一次,就会删除每个重复分组中的第一条
注:如果不加 top 1000 会报错,因为子查询使用了group by 必须要指定返回行数,根据数据量定就行
select top 1000 (
select top 1 rec_id from met_treasure_hunt_box_rec b where a.userCode=b.userCode and a.box_type=b.box_type
) rec_id from met_treasure_hunt_box_rec a group by a.userCode,a.box_type having count(1)>1 order by count(1) desc
)
边栏推荐
- 企业应当实施的5个云安全管理策略
- Focusing on data sources, data quality and model performance to build a credit profile of small and micro enterprises
- String is a reference type
- 飞书更新招聘功能 候选人可选择面试时间
- 全面认识MOS管,一篇文章就够了
- 罗振宇的A股梦,咋这么难圆?
- 接入华为游戏防沉迷,点击防沉迷弹窗后游戏闪退
- 什么是 DevOps?看这一篇就够了!
- 编辑器vscode Already included file name ‘xxx‘ differs from file name ‘xxx‘ only in casing报错
- Two years of independent development experience Programmers tell us the experience of making money (listen to the masters who really make money)
猜你喜欢
随机推荐
OAuth2图文快速入门
广告电商系统开发之订单处理
Cool and efficient data visualization big screen, it's really not that difficult to do!丨Geek Planet
[牛客网]OR63删除公共字符
编辑器vscode Already included file name ‘xxx‘ differs from file name ‘xxx‘ only in casing报错
MySQL - Explain explanation
如何让 WPF 程序更好地适配 UI 自动化
String is a reference type
大神们都在用的神器,你和大神只差一个它!!
年轻人为什么不喜欢买蒙牛、伊利了?
break与continue超详解!!!
干货丨数学规划视角下的分货优化解题思路
"Lonely Walking on the Moon" is a powerful medicine, it can't cure the internal friction of happy twist
【VSCode】一文详解vscode下安装vim后无法使用Ctrl+CV复制粘贴 使用Vim插件的配置记录
Small program on how to play in the construction of e-government service platform value
Programmer Qixi Gift - How to quickly build an exclusive chat room for your girlfriend in 30 minutes
Django框架MySQL数据库到models模型的映射关系
Cache character stream
“蔚来杯“2022牛客暑期多校训练营2 G、J、K
Django使用腾讯云发送短信并存入redis









