selectsc.*,(--子查询的意思是在score表中找出与当前记录cid相同,但score大于当前记录的score(sc.score)的数目+1。--那样的话:如果是0,则证明该条记录是表示的是该班的第一名,如果是1,在表示该班的第二名,以此类推。selectcount(*)fromScoreasawherea.cid=sc.cidanda.score>sc.score--所以后面加了个1)+1aspxfromScoreasscorderbysc.cid,px;做了个测试:
SETFOREIGN_KEY_CHECKS=0;--------------------------------Tablestructureforscore------------------------------DROPTABLEIFEXISTS`score`;CREATETABLE`score`(`id`int(11)NOTNULLAUTO_INCREMENT,`cid`int(11)DEFAULTNULL,`score`int(11)DEFAULTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=8DEFAULTCHARSET=utf8;--------------------------------Recordsofscore------------------------------INSERTINTO`score`VALUES('1','1','80');INSERTINTO`score`VALUES('2','1','70');INSERTINTO`score`VALUES('3','1','90');INSERTINTO`score`VALUES('4','2','80');INSERTINTO`score`VALUES('5','3','70');INSERTINTO`score`VALUES('6','3','60');INSERTINTO`score`VALUES('7','2','50');运行上面的sql查询,结果是:
mysql>selectsc.*,(->selectcount(*)fromScorewherecid=sc.cidandscore>sc.score->)+1aspx->fromScoreasscorderbysc.cid,px;+----+------+-------+------+|id|cid|score|px|+----+------+-------+------+|3|1|90|1||1|1|80|2||2|1|70|3||4|2|80|1||7|2|50|2||5|3|70|1||6|3|60|2|+----+------+-------+------+7rowsinset(0.00sec) |