MySQL 跳过表中的n行

备注:测试数据库版本为MySQL 8.0

一.需求

需要显示emp表中根据ename排序的基数行,跳过偶数行

二.解决方案

求出行号,然后通过mod取余函数跳过偶数行

-- 传统写法
select x.ename
from 
(
select  e.ename,
        (select count(*) from emp d where d.ename <= e.ename) rn
from emp e
order by e.ename
) x
where mod(rn,2) = 1;

-- MySQL 8.0分析函数写法
SELECT x.ename
from 
(
SELECT e.ename,
       row_number() over w as rn
from emp e
window w as ( order by e.sal )
) x
where mod(rn,2) = 1;

测试记录

mysql>
mysql> select x.ename
    -> from
    -> (
    -> select  e.ename,
    ->         (select count(*) from emp d where d.ename <= e.ename) rn
    -> from emp e
    -> order by e.ename
    -> ) x
    -> where mod(rn,2) = 1;
+--------+
| ename  |
+--------+
| ADAMS  |
| BLAKE  |
| FORD   |
| JONES  |
| MARTIN |
| SCOTT  |
| TURNER |
+--------+
7 rows in set (0.00 sec)

mysql> SELECT x.ename
    -> from
    -> (
    -> SELECT e.ename,
    ->        row_number() over w as rn
    -> from emp e
    -> window w as ( order by e.sal )
    -> ) x
    -> where mod(rn,2) = 1;
+--------+
| ename  |
+--------+
| SMITH  |
| ADAMS  |
| MARTIN |
| TURNER |
| CLARK  |
| JONES  |
| FORD   |
+--------+
7 rows in set (0.00 sec)

你可能感兴趣的:(#,MySQL,CookBook,MySQL从小工到专家之路,数据库,mysql,sql,跳过表中的行)