You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何MySQL中IFNULL函数返回值为字符串而非整数(LeetCode第176题)

LeetCode第176题:第二高工资

输入

Employee表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

期望输出

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

执行的SQL语句

select IFNULL((select max(salary) 
from employee 
where salary < (select max(salary) from employee)),'null') as SecondhighestSalary;

问题

实际输出结果为:

{"headers": ["SecondhighestSalary"], "values": [["200"]]}

而期望输出结果为:

{"headers": ["SecondHighestSalary"], "values": [[200]]}

为何输出中的200以字符串类型呈现而非整数类型?


解答

问题根源在IFNULL函数的第二个参数:你传入的是带单引号的字符串'null',但第一个参数是max(salary)返回的整数类型。

SQL中,当IFNULL的两个参数类型不一致时,会自动做类型转换——字符串类型的优先级高于数值类型,所以原本的整数200会被强制转为字符串,最终输出带引号的"200"。

要解决这个问题,只需把第二个参数的'null'改成不带引号的NULL即可。修改后的SQL语句如下:

select IFNULL((select max(salary) 
from employee 
where salary < (select max(salary) from employee)), NULL) as SecondHighestSalary;

此时IFNULL的两个参数都是数值/NULL类型,结果会保持整数类型,输出就是不带引号的200了。

内容的提问来源于stack exchange,提问作者SM .PRITHIV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:01:18