PostgreSQL使用distinct关键字给单独的几列去重
PostgreSQL去重问题一直困扰着我,distinct和group by远不如MySQL用起来随便,但是如果掌握了规律,还是和MySQL差不多的
主要介绍的是distinct关键字
select distinct id,name,sex,age from student
假如有一张student表,字段如上图,我查询student表中所有信息用distinct去重(上面的SQL语句),pgsql就会根据所有的字段通过算法取得重复行的第一行,但是很明显,ID这个字段我在设计的时候不会让它重复,所以相当于没有去重
我想只根据name和age去重怎么办?
可以这么写
select distinct on (name,age) id,name,sex,age from student
这样就会只根据name和age去重了
总结一下:distinct on (),括号里面的内容是要去重的列,括号外面的内容是你要查询展示的列,两者没有关系,你可以根据某些列去重不必将他们查询出来,最后这个举一个例子就是:
我要查询name和age,根据name和sex去重:
select distinct on (name,sex) name,age from student