我有一个名为Employee
的表,它是空的,这是有关列的信息:
mysql> SHOW COLUMNS FROM Employee;
+--------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
| Salary | int(11) | YES | | NULL | |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
我试图显示最高工资,如果没有最高工资(假设表现在是空的情况),则返回null:
mysql> SELECT if (min(Salary) = max(Salary), null, min(Salary)) FROM Employee ORDER BY Salary;
+---------------------------------------------------+
| if (min(Salary) = max(Salary), null, min(Salary)) |
+---------------------------------------------------+
| NULL |
+---------------------------------------------------+
1 row in set (0.00 sec)
很好,它有效。然后我试图显示第二个最高薪水,如果没有第二个最高薪水(假设该表现在是空的情况),则返回null:
mysql> SELECT if (min(Salary) = max(Salary), null, min(Salary)) FROM Employee ORDER BY Salary DESC LIMIT 1,1;
Empty set (0.00 sec)
它返回Empty set
而不是NULL
,为什么?在这种情况下如何显示NULL?
答案 0 :(得分:1)
我的猜测是LIMIT
在您的AGGREGATE
功能之后有用,您必须使用subquery
。您可以尝试以下查询:
SELECT if (min(Salary) = max(Salary), null, min(Salary))
FROM (
SELECT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1,1;
) T
答案 1 :(得分:0)
看起来您的问题在限制条款中。
尝试使用LIMIT 0, 1
代替。 MySQL的限制为0索引,这意味着您的查询当前正在尝试获取不存在的第二条记录。
尝试:
SELECT
IF (MIN(Salary) = MAX(Salary),
null,
MIN(Salary))
FROM Employee
ORDER BY Salary DESC
LIMIT 0,1;