sql中不重复的记录(distinct、group by的用法)

distinct这个关键字用来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是distinct只有用二重循环查询来解决,而这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的。

例子:

table表:

字段1 字段2
id name
1   a
2   b
3   c
4   c
5   b

库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。

比如想用一条语句查询得到name不重复的所有数据,那就必须使用distinct去掉多余的重复记录。

select distinct name from table;
得到的结果是:
----------
name
   a
   c

好像达到效果了,可是,想要得到的是id值呢?改一下查询语句吧:

select distinct name, id from table;
结果会是:
----------
id name
 1    a
 2    b
 3    c
 4    c
 5    b

distinct怎么没起作用?作用是起了的,不过它同时作用了两个字段,也就是必须得id与name都相同的才会被排除。

我们再改改查询语句:

select id, distinct name from table;

很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。
--------------------------------------------------------
下面方法可行:

select *, count(distinct name) from table group by name;

结果:
id name count(distinct name)
1    a        1
2    b        1
3    c        1

最后一项是多余的,不用管就行了,目的达到:
group by 必须放在 order by 和 limit之前,不然会报错。


distinct 多列问题 group by 解决

表 table1
id RegName PostionSN PersonSN
1 山东齐鲁制药   223      2
2 山东齐鲁制药   224      2
3 北京城建公司   225      2 
4 科技公司      225      2

我想获得结果是

id RegName PostionSN PersonSN
1 山东齐鲁制药 223 2
3 北京城建公司 225 2
4 科技公司    225 2 

sql文:

select distinct RegName,PostionSN,PersonSN from table1;

如果查询的是多列 distinct 用和不用一样,只能用group by

用group by RegName
select * from table1 where id in (select min(id) from table1 group by RegName) and PersonSN=2;

 转自:

http://www.jb51.net/article/24717.htm

http://www.itpub.net/thread-391828-1-1.html

posted @ 2013-01-10 00:43  horizon~~~  阅读(2339)  评论(0编辑  收藏  举报