数据库相关算法题 V1

20 篇文章 0 订阅

超过经理收入的员工

超过经理收入的员工显然是要将同一张表,作为经理和员工表连接。这里存在两种方法,一种是采用WHERE

SELECT
    a.Name AS 'Employee'
FROM
    Employee AS a,
    Employee AS b
WHERE
    a.ManagerId = b.Id
        AND a.Salary > b.Salary

另一种是使用JOIN

SELECT
     a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
     ON a.ManagerId = b.Id
     AND a.Salary > b.Salary

https://leetcode.cn/problems/employees-earning-more-than-their-managers/

从不订购的客户

最先想到的方法是找到所有订购过的,然后排除

select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders
)

另一种巧妙的方法是左连接筛选

SELECT name AS 'Customers'
FROM Customers
LEFT JOIN Orders ON Customers.Id = Orders.CustomerId
WHERE Orders.CustomerId IS NULL

https://leetcode.cn/problems/customers-who-never-order/description/

删除重复的电子邮箱

DELETE p1 FROM Person p1,
    Person p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id

居然不能select后update,还要通过一个中间表去解决

https://blog.csdn.net/fdipzone/article/details/52695371

https://leetcode.cn/problems/delete-duplicate-emails/description/

销售员

本题的关键在于多表连接,三表之间的连接与两表是一致的

SELECT
    s.name
FROM
    salesperson s
WHERE
    s.sales_id NOT IN (SELECT
            o.sales_id
        FROM
            orders o
                LEFT JOIN
            company c ON o.com_id = c.com_id
        WHERE
            c.name = 'RED')

https://leetcode.cn/problems/sales-person/description/

第二高的薪水

本题的关键点在于过滤掉重复的以及null的处理

对于前者直接采用distinct关键字,而后者可以

  • 使用临时表,将空数据转为null
  • 采用ifnull,为空返回第二个参数
SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

https://leetcode.cn/problems/second-highest-salary/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值