在MySQL使用中,經(jīng)常需要查詢每個(gè)分組的前幾條記錄(查詢分組后每一個(gè)組的前幾項(xiàng)),下面寫了個(gè)簡(jiǎn)單的例子說(shuō)明下SQL的寫法。簡(jiǎn)單的表設(shè)計(jì)如下,要求每個(gè)班總分排名最前的前兩條數(shù)據(jù)。 測(cè)試表語(yǔ)句如下: create table test(id int unsigned not null auto_inc
在MySQL使用中,經(jīng)常需要查詢每個(gè)分組的前幾條記錄(查詢分組后每一個(gè)組的前幾項(xiàng)),下面寫了個(gè)簡(jiǎn)單的例子說(shuō)明下SQL的寫法。簡(jiǎn)單的表設(shè)計(jì)如下,要求每個(gè)班總分排名最前的前兩條數(shù)據(jù)。
測(cè)試表語(yǔ)句如下:
create table test(id int unsigned not null auto_increment primary key,name varchar(10),class varchar(20),score varchar(20)); insert into test(name, class, score) values ('gonn', '6(1)', '299'); insert into test(name, class, score) values ('yyun', '6(1)', '259'); insert into test(name, class, score) values ('lin', '6(1)', '289'); insert into test(name, class, score) values ('mei', '6(1)', '277'); insert into test(name, class, score) values ('xj', '6(2)', '287'); insert into test(name, class, score) values ('zhl', '6(2)', '277'); insert into test(name, class, score) values ('lwjs', '6(2)', '257'); insert into test(name, class, score) values ('lulu', '6(2)', '265');
運(yùn)行以上SQL,得到的表結(jié)構(gòu)如下:
mysql> SELECT * FROM test; +----+------+-------+-------+ | id | name | class | score | +----+------+-------+-------+ | 1 | gonn | 6(1) | 299 | | 2 | yyun | 6(1) | 259 | | 3 | lin | 6(1) | 289 | | 4 | mei | 6(1) | 277 | | 5 | xj | 6(2) | 287 | | 6 | zhl | 6(2) | 277 | | 7 | lwjs | 6(2) | 257 | | 8 | lulu | 6(2) | 265 | +----+------+-------+-------+ 8 rows in set
mysql> SELECT a.id,a.name,a.class,a.score FROM test a LEFT JOIN test b on a.class = b.class and a.score < b.score GROUP BY a.id,a.name,a.class,a.score HAVING count(b.id) < 2 ORDER BY a.class,a.score DESC; +----+------+-------+-------+ | id | name | class | score | +----+------+-------+-------+ | 1 | gonn | 6(1) | 299 | | 3 | lin | 6(1) | 289 | | 5 | xj | 6(2) | 287 | | 6 | zhl | 6(2) | 277 | +----+------+-------+-------+ 4 rows in set
mysql> SELECT * FROM test a WHERE 2 >(SELECT count(*) FROM test WHERE class = a.class and score>a.score) ORDER BY a.class,a.score DESC; +----+------+-------+-------+ | id | name | class | score | +----+------+-------+-------+ | 1 | gonn | 6(1) | 299 | | 3 | lin | 6(1) | 289 | | 5 | xj | 6(2) | 287 | | 6 | zhl | 6(2) | 277 | +----+------+-------+-------+ 4 rows in set
這里列出了多種SQL語(yǔ)句的實(shí)現(xiàn)方法,有些是MySQL特有的(Limit, 其它數(shù)據(jù)庫(kù)可根據(jù)實(shí)際更改,比如oracle的rownum,MS SQL SERVER 的 top,..),有時(shí)是SQL標(biāo)準(zhǔn)支持的。但效率上和應(yīng)用的場(chǎng)合或許不同。具體應(yīng)用時(shí)可根據(jù)實(shí)際表中的記錄情況,索引情況進(jìn)行選擇。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com