码迷,mamicode.com
首页 > 数据库 > 详细

mysql中distinct

时间:2018-07-07 22:33:01      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:htm   key   cat   tab   ase   name   current   style   amp   

本事例实验用表task,结构如下

MySQL> desc task;

+-------------+------------+------+-----+-------------------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------------+------------+------+-----+-------------------+-------+

| PLAYER_ID | bigint(20) | NO | PRI | NULL | |

| TASK_ID | int(11) | NO | PRI | NULL | |

| TASK_STATUS | tinyint(4) |NO | | NULL | |

| CREATE_DATE | datetime | YES | | NULL | |

| UPDATE_DATE |timestamp | NO | | CURRENT_TIMESTAMP | |

+-------------+------------+------+-----+-------------------+-------+

 

1 Distinct 位置

单独的distinct只能放在开头,否则报错,语法错误

mysql> Select player_id,distinct(task_id) from task;

ERROR 1064 (42000): You havean error in your SQL syntax; check the manual that

corresponds to your MySQLserver version for the right syntax to use near ‘disti

nct(task_id) from task‘ atline 1

现在把distinct放在开头

mysql> Select distinct(task_id),taskid from task;

查询成功

与其他函数使用时候,没有位置限制如下

Select player_id,count(distinct(task_id))from task;

这种情况下是正确的,可以使用。

2 Distinct用法

a.在count计算不重复的记录的时候能用到
比如SELECT COUNT( DISTINCT player_id ) FROM task;
就是计算talbebname表中id不同的记录有多少条

b,在需要返回记录不同的id的具体值的时候可以用
比如SELECT DISTINCT player_id FROM task;
返回talbebname表中不同的id的具体的值

c.上面的情况2对于需要返回mysql表中2列以上的结果时会有歧义
比如SELECT DISTINCT player_id, task_id FROM task;
实际上返回的是player_id与task_id同时不相同的结果,也就是DISTINCT同时作用了两个字段,必须得player_id与task_id都相同的才被排除了,与我们期望的结果不一样,我们期望的是player_id不同被过滤

在这种情况下,distinct同时作用了两个字段,player_id,task_id

d.这时候可以考虑使用group_concat函数来进行排除,不过这个mysql函数是在mysql4.1以上才支持的

e. 其实还有另外一种解决方式,就是使用
SELECT player_id, task_id, count(DISTINCT player_id) FROM task.
虽然这样的返回结果多了一列无用的count数据(有时也许就需要这个数据)

f 同时我们还可以利用下面的方式解决b遇到的歧义问题通过group by 分组

select player_id,task_id from task group by player_id

group by 必须放在 order by 和 limit之前,不然会报错

distinct 优化

请参考:http://isky000.com/database/mysql_distinct_implement

 https://www.cnblogs.com/lushilin/p/6187743.html

mysql中distinct

标签:htm   key   cat   tab   ase   name   current   style   amp   

原文地址:https://www.cnblogs.com/tianzeng/p/9278132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!