SQL语句对某字段去重?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL语句对某字段去重?相关的知识,希望对你有一定的参考价值。

select prokey,classname from pro,class where pro.prokey=class.classkey

sql语句通过DISTINCT关键字去重, 用于返回唯一不同的值。DISTINCT关键字需要搭配SELECT 语句使用,语法为SELECT DISTINCT 列名称 FROM 表名称。如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中,否则会出现错误。

扩展资料:

distinct这个关键字用来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是distinct只有用二重循环查询来解决,而这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的。

distinct必须放在开头,distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。

参考技术A 如果你只选prokey话可以使用distinct关键字
select distinct prokey from pro,class where pro.prokey=class.classkey
但是因为classname不同,即使使用distinct关键字:
select distinct prokey,classname from pro,class where pro.prokey=class.classkey
也会出现图中所示的结果。
参考技术B select PROKEY,listagg(classname,',') WITHIN GROUP(ORDER BY classname)
from pro,class
where pro.prokey=class.classkey
GROUP BY prokey,classname
没太懂想要什么,如果用distinct你的classname不重复也会报出的。除非你只select的prokey一个字段。
我给的是用listagg,如果有多个classname用“,”分隔,练成一条记录。可以参考试试。
参考技术C 你这几行的资料都是不一样的啊 没什么重复,说 出你想要的效果吧 参考技术D 使用distinct语句本回答被提问者采纳

mysql 对某几个字段去重

mysql 对某几个字段去重
比如select id,a,b,c from table;
现在怎么对id,和a同时相同的字段去重。
用distinct只能对id,a,b,c全相同的去重,各位有什么好得办法没。

-------------------部分字段重复---------------------
--1.加索引的方式
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
Alter IGNORE table test_2 add primary key(id);
select * from test_2;
+----+-------+
| id | value |
+----+-------+
| 1 | 2 |
| 2 | 3 |
+----+-------+
我们可以看到 1 3 这条记录消失了
我们这里也可以使用Unique约束 因为有可能列中有NULL值,但是这里NULL就可以多个了..
--2.联合表删除
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
delete A from test_2 a join (select MAX(value) as v ,ID from test_2 group by id) b
on a.id=b.id and a.value<>b.v;
select * from test_2;
+------+-------+
| id | value |
+------+-------+
| 1 | 3 |
| 2 | 3 |
+------+-------+
--3.使用Increment_auto也可以就是上面全部字段去重的第二个方法
--4.容易错误的方法
--有些朋友可能会想到子查询的方法,我们来试验一下
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
delete a from test_2 a where exists(select * from test_2 where a.id=id and a.value<value);
/*ERROR 1093 (HY000): You can't specify target table 'a' for update in FROM clause*/

目前,您不能从一个表中删除,同时又在子查询中从同一个表中选择。
参考技术A 分组下不就行了,delete from table where rowid not in (selelct max(rowid) from table group by id,a);
这样就把重复的数据删掉了。本回答被提问者和网友采纳
参考技术B 提供个思路,用select a,b,c,count(distinct id) from table可以只对id相同的去重

以上是关于SQL语句对某字段去重?的主要内容,如果未能解决你的问题,请参考以下文章

sql语句去重

SQL多个字段如何去重

sql语句去重distinct方法是啥?

sql语句去重

SQL语句怎么对单个字段去重,并且要显示所有列

SQL语句怎么对单个字段去重,并且要显示所有列