MySQL-刷题记录

Posted AugusKong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL-刷题记录相关的知识,希望对你有一定的参考价值。

  1. Second Highest Salary
SELECT MAX(Salary)
FROM Employee
WHERE Salary < (SELECT max(Salary) FROM Employee)
  1. Nth Highest Salary
CREATE FUNCTION getNthHightestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
    RETURN (
        SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1(LIMIT M, 1 是LIMIT 1 OFFSET M的简写) OFFSET M表示从表的M+1行(0-based开始查找
    );
END
  1. Shortest Distance in a Line
    每个点与其他所有的点都做差比较,最后返回最小值
    Self Join: table joined with itself
    SELECT column_name(s) FROM table T1, table T2 WHERE condition
SELECT MIN(ABS(P1.x - P2.x)) AS shortest FROM point AS P1
JOIN point AS P2 ON P1.x > P2.x(等价于P1.x <> P2.x <>符号表示不相等)
SELECT MIN(ABS(P1.x - P2.x)) AS shortest FROM 
point  P1, point P2 
WHERE P1.x > P2.x

KEYWORD LIST

LIMIT: Specify the number of records to return in the result set
LEFT JOIN: Returns all rows from the left table, and the matching rows from the right table
NOT NULL: enforces a column to not accept NULL values CREATE TABLE Persons( ID int NOT NULL, Name varchar(25) NOT NULL);
ROUND(number, decimals):: number: Required The number to be rounded decimals: Optional, the number of decimal places to round number it. 默认是整型
CASE FUNCTION
语法:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;

IF FUNCTION

WHERE OR条件 与 UNION表的效率差别

  1. Friend Requests I: Overall Acceptance Rate
    必须找到unique 的acceptance 以及 request
SELECT
    IFNULL(
        (SELECT ROUND(COUNT(DISTINCT  requester_id, accepter_id)/COUNT(DISTINCT sender_id, send_to_id), 2)
FROM request_accepted, friend_request), 0) 
AS accept_rate; 
  1. Tree Node
id p_id
1 null
2 1
3 1
4 2
5 2

Each node in the tree can be one of three types:
Leaf / Root / Inner

通过Query找出每个node的Type

Query之间的 连接组合可以使用的SQL语法:

  • CASE WHEN关键字
  • IF关键字
  • UNION关键字
SELECT id, ‘Root‘ AS Type
FROM tree 
WHERE p_id IS NULL
UNION

SELECT id, ‘Leaf‘ AS Type
FROM tree
WHERE id NOT IN (SELECT DISTINCT p_id FROM tree WHERE p_id IS NOT NULL)
AND p_id IS NOT NULL
UNION

SELECT id, ‘Inner‘ AS Type
FROM tree
WHERE id IN (SELECT DISTINCT p_id FROM tree WHERE p_id IS NOT NULL) 
AND p_id IS NOT NULL
ORDER BY id;
--使用CASE关键词
SELECT id AS `Id`, 
(CASE 
    WHEN p_id is null THEN ‘ROOT‘
    WHEN id IN (SELECT p_id FROM tree WHERE p_id IS NOT NULL) THEN ‘Inner‘
    ELSE ‘Leaf‘ 
END) as Type
FROM tree
GROUP BY id; 
  1. Rank Scores










以上是关于MySQL-刷题记录的主要内容,如果未能解决你的问题,请参考以下文章

leetcode刷题MySQL题解二十一

leetcode刷题MySQL题解二十一

牛客MySQL必知必会刷题总结

Java工程师面试题,二级java刷题软件

每日刷题记录

bmzctf 刷题记录 zonghe