MySQL的题目不多,只有寥寥十几道,梳理如下
简单:
第二高的薪水:
自己写的傻乎乎的SQL:
SELECT SUM(Salary) AS SecondHighestSalary
FROM employee
WHERE id = (
SELECT id
FROM employee
GROUP BY salary
ORDER BY Salary DESC
LIMIT 1, 1
)
说起来还是自己对MySql不够熟悉,通过的时候我还在想,这种SQL到底有什么用?根本不可能放线上运行,看了其他人的答案,五花八门,发现自己是真的太年轻了,选个自己觉得比较好的
他人答案:
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary)
FROM Employee)
虽然看网站的给的数据,在效率上看不出来,不够感觉还是应该他人的sql更好些,具体也不好说。
寻找重复的电子邮箱:
SQL:
SELECT email
FROM person
GROUP BY email
HAVING COUNT(email) > 1
他人的差不多,感觉还是自己的比较好吧
超过经理收入的员工
SQL:
SELECT a.name AS Employee
FROM employee a, employee b
WHERE a.managerid = b.id
AND a.salary > b.salary
从不订购的客户 :
SQL:
SELECT a.name AS Customers
FROM Customers a
LEFT JOIN Orders b ON a.id = b.CustomerId
WHERE b.id IS NULL
交换工资:
SQL:
UPDATE salary
SET sex = if(sex = "m", "f", "m")
上升的温度:
SQL:
SELECT a.id
FROM Weather a, weather b
WHERE a.Temperature > b.Temperature
AND a.RecordDate = date_add(b.RecordDate, INTERVAL 1 DAY)
赶脚这个还是有点难的和难理解的,一开始我还理解错了题意,甚至还是我偶然出错通过的,事后分析了一会才分析出来。
第一个条件a.Temperature > b.Temperature当然不用说,今天的要比昨天的温度更高,说一下a.RecordDate=date_add(b.RecordDate, interval 1 day),题意是今天的比前一天的更高,而不加后面那个条件,会选出所有比今天温度更低的日期,这个等式保证了b.RecordDate是前一天,因为b.RecordDate+1天 == 今天。
相比之下,这种写法则更容易理解:
SELECT w1.Id
FROM weather w1
INNER JOIN weather w2
ON w1.Temperature > w2.Temperature
AND DATEDIFF(w1.RecordDate, w2.RecordDate) = 1;
大的国家:
SQL:
SELECT name, population, area
FROM World
WHERE population > 25000000
OR area > 3000000;
超过5名学生的课:
SQL:
SELECT class
FROM (
SELECT DISTINCT student, class
FROM courses
) a
GROUP BY class
HAVING COUNT(class) >= 5
感觉他人更好的SQL:
SELECT class
FROM courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5
有趣的电影:
SQL:
SELECT *
FROM cinema
WHERE id & 1
AND description <> "boring"
ORDER BY rating DESC
至此,简单部分完。中级难度开始。