mysql中去重 用group by优化distinct 用法

mysql中去重 用group by优化distinct 用法,第1张

在使用 MySQL 时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段,例如有如下表user:

用distinct来返回不重复的用户名:select distinct name from user,结果为:

这样只把不重复的用户名查询出来了,但是用户的id,并没有被查询出来:select distinct name,id from user,这样的结果为:

distinct name,id 这样的mysql 会认为要过滤掉name和id两个字段都重复的记录,如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数。

如果要查询不重复的记录,有时候可以用group by :

select id,name from user group by name

这个表应该有个id吧

delete from tbl where id not in

(select id from (select id from tbl group by month having count(month)>1) as a)

mysql不支持在同一个表查询之后,做修改、删除 *** 作。

删除的思路是,

1、select id from tbl group by month having count(month)>1 找到需要保留的id

2、 select id from (select id from tblgroup by month having count(month)>1) as a

把需要保留的结果指定新的表名,找到保留id

3、执行删除 *** 作

过滤重复数据

有些 MySQL 数据表中可能存在重复的记录,有些情况我们允许重复数据的存在,但有时候我们也需要删除这些重复的数据。

如果你需要读取不重复的数据可以在 SELECT 语句中使用 DISTINCT 关键字来过滤重复数据。

你也可以使用 GROUP BY 来读取数据表中不重复的数据:

资料来源:树懒学堂


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/7683352.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-08
下一篇 2023-04-08

发表评论

登录后才能评论

评论列表(0条)

保存