日期:2014-05-16 浏览次数:20913 次
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');
SELECT a.id,a.regname,a.name,a.type FROM teacher a LEFT JOIN teacher b ON b.name=a.name AND b.id>a.id GROUP BY a.id,a.regname,a.name,a.type HAVING COUNT(b.id) < 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 (0.00 sec) 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 (0.02 sec) mysql>
------解决方案--------------------
SELECT A.NAME,COUNT(*) FROM `teacher` A
LEFT JOIN `teacher` B
ON A.`NAME`=B.`NAME` AND A.`ID`>=B.`ID`
看看结果