如何 distinct 只对一个字段有用,同时可以查出其他字段

查询一个字段确实是没问题的

SELECT DISTINCT task_id from reports
image.png

但我想再查询多个字段呢,只想task_id是唯一

SELECT DISTINCT task_id, candidate from reports
image.png

并没有能生效,这个其实是DISTINCT(task_id, candidate),task_id, candidate都相同的才会被排除。但我只想task_id是唯一就行,不关心candidate,但是需要查询出candidate。

DISTINCT只能放在首个字段前面,那怎么办呢?

尝试用group_concat(distinct task_id)配合group by task_id看能不能成功。

SELECT *,count(DISTINCT task_id) from reports group by task_id
image.png

报错

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sql_study.reports.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by, Time: 0.000000s

mysql 5.7以后的版本数据库的默认模式设置成了 only_full_group_by模式,而在执行的sql里有一些重复的行group by 的时候mysql 不知道选择哪一个行。除非你关闭only_full_group_by模式。

最终解决方法

这中情况不能用distinct ,group by 应该也不行。可以考虑 row_number() over(partition by ) (对想要的字段分组) ,然后取第一条数据,你这个查询只能去除数据,要不然没办法实现这种查询。

select task_id,candidate from 
(select task_id,candidate, row_number() over(partition by task_id) rn from reports) ac
where ac.rn=1;
image.png

终于成功了。。。撒花。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容