mysql使用distinct注意事项

1.mysql使用distinct的使用 一定要位于 查询的最前端:


  实例:

select distinct
sla_code,id,sla_type,sla_place,sla_rank

from sj_level_application 


如果放在后面则报错

如:

2.select td,sla_type,sla_place,sla_rankdistinct sla_code

from sj_level_application 

对单个字段distinct的同时,能够查询到其他字段:
select *, count(distinct name) from table group by name     :方法一
select id, name from table group by name :方法二

3.group by 分组
实例:
aa表       a          b
                 123       10
                 123       12
                 1234      11
                 1234      14
                 1234      14
首先 group 是用来分组的  不是过滤重复项的。重复项删除语句 DISTINCT用这个 。 select DISTINCT(a) from aa
结果就是     a
             123
             1234

group by用来分组的
select a, sum(b) from aa group by a
sum意思是总和。结果就是
    a       b
    123     22
    1234    25
语句的目的是以a为目标 需要知道 相同名字的物品   在b列一共有多少数量总和
select a,count(b)  from aa group by a
count 意思行数总和   结果就是
    a      b
    123      2
    1234     2
语句目的是  相同名字的物品 一共有几行

DISTINCT:

譬如要得到guan_type和data_source_type这两个字段的distinct值:

select DISTINCT(CONCAT(guan_type, data_source_type)) AS type, guan_type, data_source_type from guan_version where status=1 and last_changed_date<="2011-10-25 11:00:00";


文章来源:http://blog.sina.com.cn/s/blog_6e70abbd0100z6uz.html

你可能感兴趣的:(mysql笔记)