数据库相关算法题 V1

超过经理收入的员工

超过经理收入的员工显然是要将同一张表,作为经理和员工表连接。这里存在两种方法,一种是采用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/

你可能感兴趣的:(db,algorithm,数据库,算法)