在SQL中,没有值要导出时,如何输出"NULL"而不是“没有要显示的结果”

In SQL, How to output "NULL" instead of " There are no results to be displayed" when there's no value to be exported

现在正在使用 MySQL v8.0。

问题是:

Write an SQL query to report the id and the salary of the second highest salary from the Employee table. If there is no second highest salary, the query should report null.

我的虚拟数据是:

Create table If Not Exists Employee (id int, salary int);
insert into Employee (id, salary) values 
(1, 100);

我的理想输出是这样的:

+------+--------+
|  id  | salary |
+------+--------+
| NULL |  NULL  |
+------+--------+

我使用 DENSE_RANK 作为解决这个问题的更直接的方法:

WITH sub AS (SELECT id,
       salary,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS num
       FROM Employee )
SELECT id, salary
FROM sub
WHERE num = 2

但是当没有第二高的薪水时,我在导出 NULL 时遇到了问题。我试过 IFNULL,但没有用。我想这是因为输出实际上不是空的,而是空的。

提前致谢。

WITH sub AS (
    SELECT id,
           salary,
           DENSE_RANK() OVER (ORDER BY salary DESC) AS num
    FROM Employee 
)
SELECT id, salary
FROM sub
WHERE num = 2
UNION ALL
SELECT NULL, NULL
WHERE 0 = ( SELECT COUNT(*)
            FROM sub 
            WHERE num = 2 );

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=31f5afb0e7e5dce9c2c128ccc49a6f42

只是让你的查询成为一个子查询,然后从一个 single-row 产生的子查询中加入在我看来是最简单的方法:

select id, salary
from (select null) at_least_one_row
left join (
    select id, salary
    from (
        select id, salary, dense_rank() over (order by salary desc) as num
        from Employee
    ) ranked_employees
    where num = 2
) second_highest_salary on true

(与只使用一次的 cte 相比,我通常更喜欢子查询;我发现这很混乱。)