LeetCode-SQL-four

作者: 皮皮大 | 来源:发表于2020-02-14 11:38 被阅读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名学生的课。

image-20200214105734486

结果应该为:

image-20200214105756143

答案

通过建立临时表来解决

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

相关文章

  • LeetCode-SQL-four

    LeetCode-SQL-four 本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中...

网友评论

    本文标题:LeetCode-SQL-four

    本文链接:https://www.haomeiwen.com/subject/jujdfhtx.html