
本文主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中会介绍题目和尽可能多的解答方案
where条件进行查询,或者使用union进行联结
group by分组和having过滤,注意使用distinct去重
where条件使用,SQL中奇偶数的判断方法
case语句和if语句的使用,
如果一个国家的面积超过300万平方公里,或者人口超过2500万,那么这个国家就是大国家。
下图是World表,编写一个SQL查询,输出表中所有大国家的名称、人口和面积。

直接通过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
有一个courses 表 ,有: student (学生) 和 class (课程)。请列出所有超过或等于5名学生的课。

结果应该为:

通过建立临时表来解决
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
编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

-- 自己解决
select id,movie,description,rating
from cinema
where description != 'boring' -- <> 也表示不等于
and id%2 =1
order by rating desc; -- 通过where的两个条件和排序解决奇偶数的判断方法
给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。
注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句

首先需要了解更新语句的基本操作:
update 表名
set 列名=修改后的值;自己的解决方案中case语句略微复杂啦,可以进行简化,如同方法2
-- 方法1:自己方案
update salary
set sex=(
case sex when 'm' then 'f'
when 'f' then 'm'
else 'other' end);
-- 方法2:使用case表达式
update salary
set sex=(case sex when 'm' then 'f' else 'm' end);-- 方法3:使用if语句
update salary set sex = if(sex='m','f','m');if(expr1,expr2,expr3):
expr1的值为true,则返回expr2的值expr1的值为false,则返回expr3的值。网上看到了一种最牛的做法:直接使用ASCII码进行转换
update salary set sex=char(ascii('m') + ascii('f') - ascii(sex));