MySQL选择后跟一个子查询

时间:2018-08-14 14:59:18

标签: mysql select subquery

为了使问题更清楚,我对问题做了一些修改。
我发现了一种奇怪的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
有人可以解释吗?谢谢

1 个答案:

答案 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 |
+---------------------+