(3万错误,NO.3),mysql中查询数据用distinct去重复并且查多个字段

来源:互联网 发布:交换机端口流量不稳定 编辑:程序博客网 时间:2024/05/30 02:22

在MYSQL中查询去重复字段使用

message表

+----+------+--------+---------+------------+| id | user | title  | content | lastdate   |+----+------+--------+---------+------------+|  1 | pzp  | biaoti | neirong | 2012-08-27 ||  2 | pzp  | p      | pzp     | 2013-04-08 ||  3 | pzp  | p      | pzp     | 2013-04-08 |+----+------+--------+---------+------------+

查询去重复字段user

select distinct user from message;
这样得到只有一个字段的数据

+------+| user |+------+| pzp  |+------+

但是想在去重复的基础上同事查询其他字段,自己想当然的这样写

错误语句:

select id,distinct user from message;select id,distinct(user) from message; select id from message where distinct user;

上网查询后的借鉴资料:http://hi.baidu.com/fcl06/item/fa6d78351896b2c02e8ec283

修正查询语句:

 select id,group_concat(distinct user) as user from message;+----+------+| id | user |+----+------+|  1 | pzp  |+----+------+
自己多练习了一下,发现这样也能查询。

distinct 在前,其他查询字段在后。

select distinct user,id,title,content,lastdate from message;+------+----+--------+---------+------------+| user | id | title  | content | lastdate   |+------+----+--------+---------+------------+| pzp  |  1 | biaoti | neirong | 2012-08-27 || pzp  |  2 | p      | pzp     | 2013-04-08 || pzp  |  3 | p      | pzp     | 2013-04-08 |+------+----+--------+---------+------------+

这样,字段顺序稍微变了下,但是不影响需要得到的结果。

所以最后自己总结两个查询去重复项的基础上查询其他字段的方法。

1.使用:select id,group_concat(distinct user) as user,title from message;

2.使用:select distinct user,id,title from message;

原创粉丝点击