为了使问题更清楚,我对问题做了一些修改。
我发现了一种奇怪的select
语法here。这是this problem的解决方案。有趣的代码是
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
;
select
后跟一个子查询。通常,select
之后应加上column
名称,如here所示。
为了更好地了解select
的用法,我在Chrome中测试了以下示例:https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all。原始的SQL
语句是
SELECT customerId FROM Customers
。
它返回91
行。
我在其中添加了外部select
:
select (SELECT customerId FROM Customers);
它仅返回一行:第一行。
我不明白为什么它只检索一行而不是全部customerId
。
有人可以解释吗?谢谢
答案 0 :(得分:0)
使用超级查询与不使用超级查询的唯一区别是,如果少于两行,则子查询将不返回任何结果...
CREATE TABLE employee
(employee_id SERIAL PRIMARY KEY
,salary INT NOT NULL
);
INSERT INTO employee VALUES
(1,100);
SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;
Empty set (0.01 sec)
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
;
+---------------------+
| SecondHighestSalary |
+---------------------+
| NULL |
+---------------------+