distinct的用法

时间:2023-03-09 01:48:59
distinct的用法

1、  Distinct 位置

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

例:SELECT Sid,DISTINCT(Sscore) score from t_student;

[SQL]SELECT Sid,DISTINCT(Sscore) score from t_student;
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT(Sscore) score from t_student' at line 1

2、正确打开方式

  SELECT DISTINCT(Sscore) score from t_student;

3、  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