mysql problems in leetcode
Questions and answers
The problems are all under: leetcode database section
And my solutions are here: my solution
177 - Nth Highest Salary
For question 177, I need to know how to use mysql function.
Delete exists same function
mysql> drop function if exists getNthHighestSalary;
change default delimiter
Since the default delimiter is;
, change it to^^
mysql> delimiter ^^
Create function
1
2
3
4
5
6
7
8
9
10
11
12mysql> create function getNthHighestSalary(N int) returns int
-> begin
-> declare k int;
-> set k = n-1;
-> return (
-> select distinct Salary from Employee
-> where Salary is not null
-> order by Salary desc
-> limit k, 1
-> );
-> end^^
Query OK, 0 rows affected (0.00 sec)Reset delimiter to its default
delimiter ;
Try to use the new function
1
2
3
4
5
6
7mysql> select getNthHighestSalary(1);
+------------------------+
| getNthHighestSalary(1) |
+------------------------+
| 900 |
+------------------------+
1 row in set (0.00 sec)
And the answer of 177 would be
1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT |
178 - Rank Scores
There are several ways to think about it.
The most straight forward:
1 | select Score, |
Use a counter:
1 | set @rk = 0; |
Or
1 | select Score, Rank |
Simpler
1 | select Score, @rk := @rk + (@pv <> (@pv:=Score)) as Rank |
180 - Consecutive Numbers
A wrong solution, do not forget there might have -1 in the table.
1 | select Num as ConsecutiveNums |
Failed case:
1 | [1, -1] |
Add another parameter:
1 | select Num as ConsecutiveNums |
Wow, it needs the nums that is emerges more than 3 times, not exactly 3 times.
1 | select distinct Num as ConsecutiveNums |
196 - Delete Duplicate Emails
1 | drop temporary table if exists t1; |
It will report:Commands out of sync; you can't run this command now
Change it to:
1 | delete from Person |
197 - Rising Temperature
My solution
1 | select Id |
And I found another solution, it is really simple and clear:
1 | select w1.Id as Id |