3個月用python刷完leetcode600題!-數據庫簡單題

算法刷多了,感覺腦子里全是漿糊了,所以做一做數據庫的題調整一下,哈哈哈哈!

175. Combine Two Tables

175. Combine Two Tables

這道題就是一道簡單的左外鏈接啦,不過犯了一個大錯誤就是,左外鏈接的鏈接條件不是寫在where里,是在關鍵詞on后面的!

select FirstName,LastName,City,State from Person left outer join Address on Person.PersonId = Address.PersonId;

176. Second Highest Salary

176. Second Highest Salary

尋找數組中第二大的數,我們只要在選擇的時候去掉最大的數就好,所以我們使用一個子查詢來解決:

select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee);

181. Employees Earning More Than Their Managers

181. Employees Earning More Than Their Managers

一開始拼命的想,用子查詢的話,怎么把managerid傳到子查詢中呢?后來豁然開朗,自鏈接不就好了嘛!

select e1.Name as Employee from Employee as e1,Employee as e2 where e1.ManagerId=e2.Id and e1.Salary > e2.Salary

182. Duplicate Emails

182. Duplicate Emails

思路簡單,用groupby分組,然后用count計數,最后用having篩選

select Email from Person group by Email having count(*) > 1

183. Customers Who Never Order

183. Customers Who Never Order

in關鍵詞的使用,使用一個子查詢查找出所有在Orders表中出現過的CustomersId即可。

select Name as Customers from Customers where id not in (select distinct CustomerId from Orders);

196. Delete Duplicate Emails

196. Delete Duplicate Emails

兩個表進行自鏈接,然后只留下id相同的部分,去掉id不同的部分,思路太神奇:

delete p1 from Person as p1,Person as p2 where p1.Email = p2.Email and p1.Id > p2.Id

197. Rising Temperature

197. Rising Temperature

這里要用到mysql的日期處理函數(http://www.cnblogs.com/ggjucheng/p/3352280.html),使用to_days函數將日期轉換為整數。

select w2.Id from Weather w1,Weather w2 where To_days(w1.Date)+1 = to_days(w2.Date) and w1.Temperature < w2.Temperature

595. Big Countries

595. Big Countries

簡單的select

select name,population,area from World where area > 3000000 or population > 25000000

596. Classes More Than 5 Students

596. Classes More Than 5 Students

要注意的是,這里的count的時候要加distinct?我覺得是胡扯。

select class from courses group by class having count(distinct student) >= 5

620. Not Boring Movies

620. Not Boring Movies

簡單的應用排序:

select * from cinema where (id % 2) = 1 and description <> 'boring' order by rating desc

627. Swap Salary

627. Swap Salary

這道題應該算簡單題里面最簡單的了吧,還真沒想到,不過看了答案感覺豁然開朗,用了二進制運算,兩個相同字母的二進制異或是0.
update salary set sex = CHAR(ASCII('f') ^ ASCII('m') ^ ASCII(sex));

也可以使用case when,第一次接觸,還不太熟悉,感覺mysql還是很強大的。
update salary set sex = case when sex ='m' then 'f' else 'm' end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容