算法刷多了,感觉脑子里全是浆糊了,所以做一做数据库的题调整一下,哈哈哈哈!
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
寻找数组中第二大的数,我们只要在选择的时候去掉最大的数就好,所以我们使用一个子查询来解决:
select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee);
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
思路简单,用groupby分组,然后用count计数,最后用having筛选
select Email from Person group by Email having count(*) > 1
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
两个表进行自链接,然后只留下id相同的部分,去掉id不同的部分,思路太神奇:
delete p1 from Person as p1,Person as p2 where p1.Email = p2.Email and p1.Id > p2.Id
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
简单的select
select name,population,area from World where area > 3000000 or population > 25000000
596. Classes More Than 5 Students
要注意的是,这里的count的时候要加distinct?我觉得是胡扯。
select class from courses group by class having count(distinct student) >= 5
620. Not Boring Movies
简单的应用排序:
select * from cinema where (id % 2) = 1 and description <> 'boring' order by rating desc
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