sql查询重复数据

样例:有一个书籍表 t_book , 查询 表中重复的书籍数据
在这里插入图片描述

方式1 使用分组(group by having)

先使用 group by 对数据分组,再使用 having 统计出分组中计数大于 1 的分组,此分组中的数据即为重复的数据

SELECT `name`,price,author,sales,stock,img_path FROM t_book 
GROUP BY `name`,price,author,sales,stock,img_path
HAVING COUNT(1) > 1

方式2 使用 join 内连接

使用 join 将一个表自己与自己相连接,连接条件on 是除id外,a表的字段数据和b表的字段数据全部相等,再使用where 筛选不满足条件是数据 a.id != b.id
最后使用 DISTINCT 过滤重复数据,的到的就是重复的数据
(如果表中不存在重复数据那 on的连接条件只会使相同的数据本身自连接,再经过where条件,查询出来的一定是空值)

SELECT DISTINCT b1.`name`,b1.price,b1.author,b1.sales,b1.stock,b1.img_path 
from t_book b1 JOIN t_book b2 on 
b1.`name` = b2.`name` and b1.price = b2.price and 
b1.author = b2.author and  b1.sales = b2.sales and 
b1.stock = b2.stock and b1.img_path = b2.img_path 
WHERE b1.id != b2.id

方式3 使用where (将join的连接改为 where 的方式)

SELECT DISTINCT b1.`name`,b1.price,b1.author,b1.sales,b1.stock,b1.img_path
from t_book b1,t_book b2 
WHERE b1.`name` = b2.`name` and b1.price = b2.price 
and b1.author = b2.author and  b1.sales = b2.sales 
and b1.stock = b2.stock and b1.img_path = b2.img_path 
and b1.id != b2.id
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值