1.现有表情况如下:
1Create table If Not Exists Employee (Id int, Salary int); 2Truncate table Employee; 3insert into Employee (Id, Salary) values ('1', '100'); 4insert into Employee (Id, Salary) values ('2', '200'); 5insert into Employee (Id, Salary) values ('3', '300');

要查出如下的结果:

如果没有第二高的Salary将返回null

2.答案
1SELECT 2 max(Salary) AS SecondHighestSalary 3FROM 4 Employee 5WHERE 6 Salary < (SELECT max(Salary) FROM Employee) 7 8SELECT DISTINCT 9 (Salary) as SecondHighestSalary 10FROM 11 Employee 12UNION 13 SELECT 14 NULL 15 ORDER BY 16 SecondHighestSalary DESC 17 LIMIT 1, 18 1 19 20 21SELECT 22 IFNULL( 23 ( 24 SELECT DISTINCT 25 Salary 26 FROM 27 Employee 28 ORDER BY 29 Salary DESC 30 LIMIT 1 OFFSET 1 31 ), 32 NULL 33 ) AS SecondHighestSalary
其中 DISTINCT 表示去重
1DISTINCT :去重 2union 表示联合查询,去重 3union all 表示联合查询,不去重,会包含重复的数据 4desc代表降序 5asc代表升序 6limit m,n 其中m是指记录开始的index,从0开始,表示第一条记录 7n是指从第m+1条开始,取n条。 8 9limit 1,1 代表取出第2条数据,共一条数据 10 11 12select * from Employee limit 2,2 13即取出第3条至第4条,2条记录如果没有2条,存在多少条即返回多少条 14 15 16 17
nullif,isnull,ifnull 的用法
1IFNULL(expr1,expr2) 2 3如果expr1不为null,则ifnull()的返回值为expr1,否则为expr2;其返回值为字符串或数字 4 5mysql> select ifnull("hello","world"); 6+-------------------------+ 7| ifnull("hello","world") | 8+-------------------------+ 9| hello | 10+-------------------------+ 111 row in set (0.00 sec) 12 13mysql> select ifnull(null,"hello"); 14+----------------------+ 15| ifnull(null,"hello") | 16+----------------------+ 17| hello | 18+----------------------+ 191 row in set (0.01 sec) 20 21mysql> select ifnull(1/0,"world"); 22+---------------------+ 23| ifnull(1/0,"world") | 24+---------------------+ 25| world | 26+---------------------+ 271 row in set (0.00 sec) 28 29isnull(expr) 的用法: 30如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。 31mysql> select isnull(null); 32+--------------+ 33| isnull(null) | 34+--------------+ 35| 1 | 36+--------------+ 371 row in set (0.01 sec) 38 39mysql> select isnull(1); 40+-----------+ 41| isnull(1) | 42+-----------+ 43| 0 | 44+-----------+ 451 row in set (0.00 sec) 46使用= 的null 值对比通常是错误的。 47 48NULLIF(expr1,expr2) 的用法: 49如果expr1 = expr2 成立,那么返回值为NULL,否则返回值为 expr1。 50这和CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END相同。 51 52mysql> select nullif(1,1); 53+-------------+ 54| nullif(1,1) | 55+-------------+ 56| NULL | 57+-------------+ 581 row in set (0.01 sec) 59 60mysql> select nullif(1,2); 61+-------------+ 62| nullif(1,2) | 63+-------------+ 64| 1 | 65+-------------+ 661 row in set (0.01 sec) 67 68mysql> 69如果参数不相等,则 MySQL 两次求得的值为 expr1 。