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;