力扣数据库实例代码--第二节

第六题

现有数据表Customers,字段为Id、Name;数据表Order,字段为Id、CostomerId

要求:请查询出从来都不订购任何东西的客户

select ifnull((Name), null) Customers from Customers where Id not in (select CustomerId from Orders);

解析:此处只需要关联查询出不在Order表中的Id是什么,使用关键字 not in

第七题

现有数据表Cinema,字段为ID、Movie、description、rating

要求:请编写SQL,找到所有影片描述非boring,且Id为奇数的影片,结果请按等级rating排列(倒叙)

select Id, movie, description, rating from Cinema where mod(id, 2)=1 and description != 'boring' order by rating desc;

解析:可以先进行筛选,再进行计算,最后进行排序,时间复杂度会降低

第八题

现有数据表Salary,字段为Id、Name、 Sex、 Salary

要求:请编写一个更新语句,将Sex中的取值进行互换,例如f换成m、m换成f,并且更新过程中没有中间临时表

update Salary set sex=case sex when 'f' then 'm' else 'f' end;

条件判断时,可以使用case when进行条件判断筛选

第九题

现有数据表Weather,字段为Id、RecordDate、Temperature

要求:请超出所有比自身前一天温度更高的所有日期的Id

select Weather.Id from Weather join Weather w on Datediff(Weather.RecordDate, w.RecordDate)=1 and Weather.Temperature>w.Temperature; 

解析:可以和自身进行关联,使用Datediff()函数,筛选出天数差一的日期,随后进行温度比较,最后得到答案

第十题

现有数据表Person,字段为Id、Email

要求:请删除Person中重复的Email,相同的Email,保留Id较小的那个

delete P1 from Person P1, Person P2 where P1.Email=P2.Email and P1.Id>P2.Id;

解析:自身与自身比较,删除相同Email但Id较大的那个

如有不合适,欢迎大家留言斧正。

猜你喜欢

转载自blog.csdn.net/qq_31307291/article/details/88392112
今日推荐