T175
思路:
題目要求無論 person 是否有地址信息 都要提供
FirstName, LastName, City, State
所以可以使用外連接
答案:
select firstname,lastname,city,state from person p left join address a on p.personid=a.personid;
T176
思路:
首先想到使用排序和limit即可得到第二高的工資
select salary from employee order by salary desc limit 1,1
但是題目要求沒有時返回null
所以在外層加一個select
同時爲了避免工資相同的情況影響排序 所以要加上distinct
答案:
select (select distinct
salary from employee order by salary desc limit 1,1) secondhighestsalary;
答案中給出的另一種解法:
T181
select e1.name Employee from employee e1,employee e2 where e1.managerid=e2.id and e1.salary>e2.salary;
T182
select email from person group by email having count(*)>=2;
T183
select name customers from customers where id not in (select customerid from orders);
另一種方法:
select name customers from customers c left join orders o on c.id=o.customerid where o.id is null;
左外連接生成的表如下
T196
子查詢:delete from person where id not in (select id from(select min(id) id from person group by email) temp)
多嵌套一層select是因爲mysql中會出現1093錯誤
連接:
T197
select w1.id from weather w1,weather w2 where DateDiff(w1.recorddate,w2.recorddate)=1 and w1.temperature>w2.temperature;
使用DateDiff函數可以得到兩個日期之間的差 爲1則爲之後一天
T595
select name,population,area from world where population>25000000 or area>3000000;
T596
select class from courses group by class having count(distinct student)>=5;
Note:
學生在每個課中不應被重複計算
所以count條件爲distinct student
T620
select * from cinema where description != 'boring' and MOD(id,2)=1 order by rating desc;
T627
使用if
update salary set sex=if(sex='m','f','m');
使用case when
update salary set sex= case sex when 'f' then 'm' else 'f' end;