使用mysql的disctinct group by查询不重复记录
更新时间:2008年08月01日 00:15:40 作者:
非常不错的方法,用mysql的group by解决不重复记录的问题,看来我需要学习的地方太多了
有个需求,一直没有解决,在google上找了半天,给出的方案没有一个能用了,最后鬼使神差搞定了。
是这样的,假设一个表:
id f_id value
1 2 a
2 2 b
3 5 c
4 9 c
5 9 a
6 6 d
id f_id value
1 2 a
2 2 b
3 5 c
4 9 c
5 9 a
6 6 d
id是主键,f_id是外键,我需要获得不重复的外键f_id的数据,如果用group by 或者distinct很容易搞定
select f_id from table group by f_id
select distinct f_id from table
但如果再想在结果中得到id值的话,不管怎么都会乱。比如我想在结果中用id进行排序,诸如”select distinct f_id, id from table order by id desc”完全白费。在google上看了大量的例子,发现需要在select中对id做手脚,让mysql知道除了f_id外,对id应该进行如何的操作。诸如Max, Min, Avg,Sun..都是可以的,于是变成以下的代码就搞定了……
select f_id, max(id) as id from table group by f_id order by id desc
搞定,网上有个文章很接近答案,但是他没有”as id”,导致在我的mysql中执行结果有误,呵呵。
是这样的,假设一个表:
id f_id value
1 2 a
2 2 b
3 5 c
4 9 c
5 9 a
6 6 d
id f_id value
1 2 a
2 2 b
3 5 c
4 9 c
5 9 a
6 6 d
id是主键,f_id是外键,我需要获得不重复的外键f_id的数据,如果用group by 或者distinct很容易搞定
select f_id from table group by f_id
select distinct f_id from table
但如果再想在结果中得到id值的话,不管怎么都会乱。比如我想在结果中用id进行排序,诸如”select distinct f_id, id from table order by id desc”完全白费。在google上看了大量的例子,发现需要在select中对id做手脚,让mysql知道除了f_id外,对id应该进行如何的操作。诸如Max, Min, Avg,Sun..都是可以的,于是变成以下的代码就搞定了……
select f_id, max(id) as id from table group by f_id order by id desc
搞定,网上有个文章很接近答案,但是他没有”as id”,导致在我的mysql中执行结果有误,呵呵。
相关文章
CentOS 7中升级MySQL 5.7.23的坑与解决方法
我们在安装升级的时候会遇到一些问题,不过可能每个人遇到的问题不一样,多找找才能解决问题哟,下面这篇文章主要给大家介绍了关于在CentOS 7中升级MySQL 5.7.23遇到的一个坑与解决方法,需要的朋友可以参考下2018-10-10Windows系统下MySQL添加到系统服务方法(mysql解压版)
这篇文章主要介绍了Windows系统下MySQL添加到系统服务方法,主要针对mysql解压版,感兴趣的朋友参考下吧2016-05-05
最新评论