赞
踩
样例:有一个书籍表 t_book , 查询 表中重复的书籍数据
先使用 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
使用 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
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。