mysql distinct 用法详解及优化

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

 MySQL> desc task;sql

+-------------+------------+------+-----+-------------------+-------+函数

| Field       | Type       | Null | Key | Default           | Extra |优化

+-------------+------------+------+-----+-------------------+-------+.net

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

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

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

| CREATE_DATE | datetime   | YES |     | NULL              |       |io

| UPDATE_DATE |timestamp  | NO   |    | CURRENT_TIMESTAMP |       |class

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

  

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

distinct 优化

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

对distinct的原理 及优化分析的很好,你们能够查看。

相关文章
相关标签/搜索