mysql 查询在一行中打印不同行的数据

mysql query prints data of different rows in one row

我正在使用 MySQL 8.0 版和 popSQL 作为编辑器。

Table:

create table account (no int, salary int);


insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);

现在,我想要最高薪水的人的薪水。 最高工资是40000,对应的是904。 但是,这个查询给了我不同的输出。

-- no and salary of max salary
select no, max(salary)
from account ;

输出为: 没有最高(工资) 901 40000

它正在打印第一个没有和最高薪水。 即不同行的数据显示在同一行中。 如何解决这个问题???

我的下一个查询遇到相同类型的问题。

-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);

输出为: 没有最高(工资) 901 30000

而预期是 902,30000。

我在堆栈溢出中搜索了不同行的数据显示在一个但没有得到任何帮助的问题。

提前致谢。

I want no and salary of person with highest salary

您不需要为此聚合。您可以按以下顺序订购并限制:

select no, salary
from account
order by salary desc
limit 1

MySQL 5.7.5 及更早版本因接受格式错误的 SQL 查询而臭名昭著。

标准SQL中,当没有GROUP BY子句时,所有列都必须聚合或不聚合。但是,您选择聚合一个,而不是另一个。这在 SQL 中是非法的,并且会导致不确定的结果。但是... MySQL 接受了。

使用它需要您自担风险。

注意:出于兼容性原因,可以在 MySQL 的未来版本中启用此不良行为。我鼓励你不要做这样的事情。

For Highest Salary

select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 1 limit 1

For Second highest salary

select no, salary from (
    select no, salary, ROW_NUMBER() OVER (partition by salary order by salary desc) as rn
    from account
) as a
where rn = 2 limit 1