企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## Mysql数据库中查询某表中第二大的数据 > leetcode记录 ``` 编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。 +----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ 例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。 +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ ``` ```mysql # 1. 查询出最大的记录,然后查询剩下记录中比该记录小的最大数据记录 select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee); # 2. 先取得最大的,然后not in 最大的那个,在剩下的取最大的就是第二个。 select max(Salary) from Employee where Salary not in (select max(Salary) from Employee); # 3. 使用limit offset select Salary from Employee order by Salary limit 1,1; select Salary from Employee order by limit 1 offset 1 ``` ## MySQL查找重复的电子邮箱 重复的电子邮箱存在多次。要计算每封电子邮件的存在次数,我们可以使用以下代码 ```mysql select Email, count(Email) as num from Person group by Email; ``` ``` | Email | num | |---------|-----| | a@b.com | 2 | | c@d.com | 1 | ``` 向 `GROUP BY` 添加条件的一种更常用的方法是使用 `HAVING` 子句,该子句更为简单高效。 ```mysql select Email from Person group by Email having count(Email) > 1; ``` 知道使用group by和having。还需要记得优先顺序。where>group by>having>order by 相比于执行速度来说,下面的更快 ```mysql select distinct a.Email from Person a, Person b where a.Email=b.Email and a.Id <> b.Id; ```