mysql表中获取去除重复的记录
1.构建表和数据
CREATE TABLE `teacher` (
`ID` bigint(20) NOT NULL COMMENT 'ID',
`REGNAME` char(200) DEFAULT NULL COMMENT '师教编号',
`NAME` char(20) NOT NULL COMMENT '教师名称',
`TYPE` int(1) DEFAULT '0' COMMENT '师教类型(0:内聘,1:外聘)',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `teacher` VALUES ('10001', 'allen', 'allen', '0');
INSERT INTO `teacher` VALUES ('10002', 'ruby', 'ruby', '0');
INSERT INTO `teacher` VALUES ('10003', 'sharon', 'sharon', '1');
INSERT INTO `teacher` VALUES ('10004', 'alpha', 'alpha', '0');
INSERT INTO `teacher` VALUES ('10005', 'alpha', 'alpha', '0');
INSERT INTO `teacher` VALUES ('10006', 'alpha', 'alpha', '0');
2.数据库记录
mysql> select * from teacher;
+-------+---------+--------+------+
| ID | REGNAME | NAME | TYPE |
+-------+---------+--------+------+
| 10001 | allen | allen | 0 |
| 10002 | ruby | ruby | 0 |
| 10003 | sharon | sharon | 1 |
| 10004 | alpha | alpha | 0 |
| 10005 | alpha | alpha | 0 |
| 10006 | alpha | alpha | 0 |
+-------+---------+--------+------+
6 rows in set
3.需要获取的记录
+-------+---------+--------+------+
| ID | REGNAME | NAME | TYPE |
+-------+---------+--------+------+
| 10001 | allen | allen | 0 |
| 10002 | ruby | ruby | 0 |
| 10003 | sharon | sharon | 1 |
| 10004 | alpha | alpha | 0 |
| 10005 | alpha | alpha | 0 |
+-------+---------+--------+------+
查询语句:mysql> select * from teacher t
where 2>(select count(*) from teacher where REGNAME=t.REGNAME and ID<t.ID);
+-------+---------+--------+------+
| ID | REGNAME | NAME | TYPE |
+-------+---------+--------+------+
| 10001 | allen | allen | 0 |
| 10002 | ruby | ruby | 0 |
| 10003 | sharon | sharon | 1 |
| 10004 | alpha | alpha | 0 |
| 10005 | alpha | alpha | 0 |
+-------+---------+--------+------+
5 rows in set
-----------------------------------------------------
解释: 说白了 就是每条语句都有一个count(*),10001,10002,10003,10004的count(*)都是0,
10005的count(*)是1,10006的count(*)就是2,取大于2的数据,就排除了id是1006的记录。
当检索到id是10006的时候,REGNAME=t.REGNAME 的记录有3条,
而符合这个条件的是ID<t.ID,分别是 10004<10006,10005<10006,
10006不小于1006,
所以当id是1006的时候,count(*)是2。
而表中REGNAME唯一的记录的count(*)是0,因为,举个例子来说,当检索id是10001的记录时, 不存在1001<1001的结果,所以count(*)是0
--------------------
还可以访问 获得更多信息
http://blog.csdn.net/acmain_chm/article/details/4126306