LeetCode-SQL-four
2020-02-14 本文已影响0人
皮皮大
LeetCode-SQL-four
本文中主要是介绍LeetCode
中关于SQL
的练习题,从易到难,循序渐进。文中会介绍题目和尽可能多的解答方案
595-找出最大的国家
题目
如果一个国家的面积超过300
万平方公里,或者人口超过2500
万,那么这个国家就是大国家。
下图是World
表,编写一个SQL查询,输出表中所有大国家的名称、人口和面积。
image
答案
答案
直接通过or来进行联结
select name, population, area -- 方法1
from world
where (area > 3000000) or (population > 25000000);
通过union来进行联结
SELECT name, population, area FROM world -- 方法2
WHERE area > 3000000
UNION
SELECT name, population, area FROM world
WHERE population > 25000000;
这道题就是这么的简单,做出来自己都不敢相信,采用的是方法1
596-超过5名学生的课
题目
有一个courses
表 ,有: student (学生) 和 class (课程)。请列出所有超过或等于5名学生的课。
![](https://img.haomeiwen.com/i5142014/1a8916917a439340.jpg)
结果应该为:
![](https://img.haomeiwen.com/i5142014/564fe2805e73cbc5.jpg)
答案
通过建立临时表来解决
select class
from (select class, count(distinct student) as num
from courses
group by class) as temp
where num >= 5;
通过having
过滤来解决,注意使用distinct
,有些可能是重复记录
select class
from courses
group by class
having count(distinct student) >= 5;
一定要注意distinct
620-有趣的电影
题目
编写一个 SQL查询,找出所有影片描述为非 boring
(不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating
排列。
image
答案
-- 自己解决
select id,movie,description,rating
from cinema
where description != 'boring' -- <> 也表示不等于
and id%2 =1
order by rating desc; -- 通过where的两个条件和排序解决
奇偶数的判断方法
- id&1
- id%2
- mod(id, 2) =1,表示对2求余数=1