Bootstrap

mysql中获取第2大的三种方法

创建表,插入数据

DROP TABLE IF EXISTS players;
CREATE TABLE `players`(
    `id` INT UNSIGNED AUTO_INCREMENT,
    `height` INT NOT NULL,
    PRIMARY KEY ( `id` )
);
INSERT INTO players VALUES(1,198),(2,226),(3,200),(4,226)
;

第一种方法

– 思路:获取降序排列后的最大值,过滤得到小于最大值的表1,查询表1中的最大值即为原表中的第二大


SELECT MAX(height) second_height 
FROM players 
WHERE height<(SELECT MAX(height) FROM players)
;

第二种方法

– 思路:降序排列,从limit 1 开始取,取第一个数
– 如果没有第二大,输出null

SELECT (
    IFNULL(
    (SELECT DISTINCT height
    FROM players
    ORDER BY height DESC
    LIMIT 1,1),
    NULL
    )
) as second_height;
-- 另一种写法
SELECT (
    IFNULL(
    (SELECT DISTINCT height
    FROM players
    ORDER BY height DESC
    LIMIT 1 OFFSET 1),
    NULL
    )
) as second_height;

MySQL8.0版本中的窗口函数

– 思路:dense_rank() over(),当出现值一样时,排序为111 2 33 444 5 66 7 8 9 这种序号方式

SELECT height se_h
FROM (SELECT height,DENSE_RANK() over(ORDER BY height DESC) as dense_h
	  FROM players) as t1
WHERE t1.dense_h=2
;
;