今天群里有人提了这么一个问题,原话是: “表T(a,b,c,d),怎么显示按c排序之后的21-30条记录。(a,b,c,d)中可能没有类似ID的属性” 我当时给出的答案是: select * from T order by c where rownum in (21, 30); 不过后来想想可能这在MySQK上是不可行的。貌似只有Oracle支持吧。 先总结些流行数据库查询前N条记录的方法吧: 1、MySQL : ;这里取N为5 select * from T order by c limit 5; 2、SQL Serve r: select top 5 * from T order by c; 3、Oracle : select * from T order by c where rownum<5; 然后我针对MySQL给出了一条语句: select A.* from T as A order by A.a limit 5 where A.a not in (select B.a from T as B order by B.a limit 3); 这条语句在我现在这个版本的MySQL上执行不了,为什么呢?错误信息是: ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/AN Y/SOME subquery' 在MySQL4.1中子查询是不能使用LIMIT的,手册中也明确指明 This version of MySQL doesn’t yet support ‘LIMIT & IN/ALL/ANY/SOME subquery’ 也就是说,这样的语句是不能正确执行的。 select * from table where id in (select id from table limit 10); 但是,只要你再来一层 就行。。如: select * from table where id in (select t.id from (select * from table limit 10)as t) This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'的意思是,这版本的 MySQL 不支持使用 LIMIT 子句的 IN/ALL/ANY/SOME 子查詢,即是支持非 IN/ALL/ANY/SOME 子查詢的 LIMIT 子查詢。 歧义点在于各生字的 apply 和組合顺序,这句子的正确結合顺序是 “This version of MySQL doesn’t yet support ((LIMIT-(IN/ALL/ANY/SOME)) subquery)” (”-”符号为hyphen ),有可能的错误理解是 “This version of MySQL doesn’t yet support ((LIMIT subquery) & ((IN/ALL/ANY/SOME) subquery))”。 所以最后我给出的答案是: select * from T as C where C.c in (select p.* from (select A.c from T as A order by A.c limit 30) as p) and C.c not in (select q.* from (select B.c from T as B order by B.c limit 21) as q); 虽然答案有点长,但是执行效率还是不算低的。如果大家有什么更好的方法 ,欢迎拍砖和指正。
From:http://hi.baidu.com/