LeetCode 数据库刷题

发现LeetCode还能做数据库的题,最近比较闲,就一起做了。题目还挺难的,中等的基本就不会了,题解大法好。

题目列表

  • 175. 组合两个表
  • 175.第二高的薪水
  • 177. 第N高的薪水
  • 178. 分数排名
  • 180. 连续出现的数字
  • 181. 超过经理收入的员工
  • 182. 查找重复的电子邮箱
  • 183. 从不订购的客户
  • 184. 部门工资最高的员工
  • 196. 删除重复的电子邮箱
  • 197. 上升的温度

175. 组合两个表

思路:left join即可

SELECT
	p.FirstName,
	p.LastName,
	a.City,
	a.State
FROM
	Person p
LEFT JOIN Address a ON p.PersonId = a.PersonId

175.第二高的薪水

思路:学习到了ifnull这个函数,当查询结果为空时,返回定义的结果。distinct去重

SELECT
	ifnull(
		(
			SELECT DISTINCT
				Salary
			FROM
				Employee
			ORDER BY
				Salary DESC
			LIMIT 1,
			1
		),
		NULL
	) AS SecondHighestSalary;

177. 第N高的薪水

思路:和前一题差不多

CREATE FUNCTION getNthHighestSalary (N INT) RETURNS INT
BEGIN

SET N = N - 1;

RETURN (
	# Write your MySQL query statement below.
	SELECT
		ifnull(
			(
				SELECT DISTINCT
					Salary
				FROM
					Employee
				ORDER BY
					Salary DESC
				LIMIT N,
				1
			),
			NULL
		)
);


END

178. 分数排名

思路:首先查出所有分数,并按照分数排序,排名通过count函数来得到。考虑统计所有大于等于该分数的人数,就是该分数的排名。

SELECT
	a.score score,
	(
		SELECT
			count(DISTINCT b.score)
		FROM
			scores b
		WHERE
			b.score >= a.score
	) rank
FROM
	scores a
ORDER BY
	a.score DESC

180. 连续出现的数字

思路:题目怎么说,sql怎么写。id用于判断连续,num用于判断相等,distinct去重

SELECT DISTINCT
	l1.num ConsecutiveNums
FROM
	LOGS l1,
	LOGS l2,
	LOGS l3
WHERE
	l1.id = l2.id - 1
AND l2.id = l3.id - 1
AND l1.num = l2.num
AND l2.num = l3.num

181. 超过经理收入的员工

思路:题目怎么说,sql怎么写

SELECT
	a. NAME Employee
FROM
	Employee a,
	Employee b
WHERE
	a.managerid = b.id
AND a.salary > b.salary

182. 查找重复的电子邮箱

思路:使用having筛选group后的数据

SELECT
	Email
FROM
	Person
GROUP BY
	Email
HAVING
	count(Email) > 1

183. 从不订购的客户

思路:left join之后,查询customerid为空的人

SELECT
	c. NAME Customers
FROM
	Customers c
LEFT JOIN Orders o ON c.id = o.customerid
WHERE
	customerid IS NULL

184. 部门工资最高的员工

思路:先将两张表inner join,得到交集部分。然后对于employee表,group by之后,选出最高的salary和departmentid。使用in语句查询出名字,不直接查出名字是因为可能有多个相同的最高工资。


SELECT
	b. NAME Department,
	a. NAME Employee,
	a.salary Salary
FROM
	(
		employee a
		INNER JOIN department b ON a.departmentid = b.id
	)
WHERE
	(a.departmentid, a.salary) IN (
		SELECT
			c.departmentid,
			max(salary)
		FROM
			employee c
		GROUP BY
			c.departmentid
	)

196. 删除重复的电子邮箱

思路:将Email和自身根据email和id两个条件inner join,查出id较大的重复数据,然后删除即可

DELETE p1.*
FROM
	person p1
INNER JOIN person p2 ON p1.email = p2.email
AND p1.id > p2.id

197. 上升的温度

思路:主要学习了DATEDIFF的使用,也可以使用date_sub,date_sub好像比较慢
DATEDIFF:

SELECT
	w2.id
FROM
	Weather w1,
	Weather w2
WHERE
	DATEDIFF(
		w2.RecordDate,
		w1.RecordDate
	) = 1
AND w1.Temperature < w2.Temperature

date_sub:

SELECT
	w2.id
FROM
	Weather w1,
	Weather w2
WHERE
	w1.RecordDate = date_sub(w2.RecordDate, INTERVAL 1 DAY)
AND w1.Temperature < w2.Temperature

你可能感兴趣的:(LeetCode)