mysql 去重案例:
select group_concat(distinct user_id), `tenant_id` , `create_time` from `dtops_db_list` where `create_time` >='2016-07-22 00:00:00' and `create_time` <='2016-07-28 23:59:59' group by `tenant_id`
1.建表语句
wjj@>create table dtstack(
-> user_id int,
-> user_name varchar(200) not null default '')engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.05 sec)
2.插入测试数据:
wjj@>insert into dtstack values(2016,'wjj1'),(2016,'wjj2'),(2017,'wjj3');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
3.现在需要对user_id字段去重:
wjj@>select distinct user_id,user_name from dtstack order by user_id limit 0,3;
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 2016 | wjj1 |
| 2016 | wjj2 |
| 2017 | wjj3 |
+---------+-----------+
3 rows in set (0.00 sec
上面的返回记录是对user_id,user_name一起去重,不是单个字段去重。
4.mysql中引入了group_concat函数,可以与group by 一起使用实现单个字段去重:
wjj]>select group_concat(distinct user_id),user_name from dtstack group by user_id order by user_id limit 0,3;
+--------------------------------+-----------+
| group_concat(distinct user_id) | user_name |
+--------------------------------+-----------+
| 2016 | wjj1 |
| 2017 | wjj3 |
+--------------------------------+-----------+
2 rows in set (0.00 sec)
解释:group_concat函数:是将相同的行组合起来
完整的语法如下:group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符'])