595
力扣596题
SQL架构
这里有张
World
表±----------------±-----------±-----------±-------------±--------------+
| name | continent | area | population | gdp |
±----------------±-----------±-----------±-------------±--------------+
| Afghanistan | Asia | 652230 | 25500100 | 20343000 |
| Albania | Europe | 28748 | 2831741 | 12960000 |
| Algeria | Africa | 2381741 | 37100000 | 188681000 |
| Andorra | Europe | 468 | 78115 | 3712000 |
| Angola | Africa | 1246700 | 20609294 | 100990000 |
±----------------±-----------±-----------±-------------±--------------+如果一个国家的面积超过300万平方公里,或者人口超过2500万,那么这个国家就是大国家。
编写一个SQL查询,输出表中所有大国家的名称、人口和面积。
例如,根据上表,我们应该输出:
±-------------±------------±-------------+
| name | population | area |
±-------------±------------±-------------+
| Afghanistan | 25500100 | 652230 |
| Algeria | 37100000 | 2381741 |
±-------------±------------±-------------+
直接使用where来约束查询的结果即可。
Select name, population, area From World
Where area > 3000000 or population > 25000000;
596
题目
有一个courses 表 ,有: student (学生) 和 class (课程)。
请列出所有超过或等于5名学生的课。
例如,表:
±--------±-----------+
| student | class |
±--------±-----------+
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
±--------±-----------+应该输出:
±--------+
| class |
±--------+
| Math |
±--------+Note:
学生在每个课中不应被重复计算。
根据课程来分组,根据提示学生在每个课中不应被重复计算所以在计算每个分组内学生数时,使用distinct
来确保学生只会被计算一次。
Select class From courses Group By class Having count(distinct student) >= 5;
620 有趣的电影
力扣题目链接
作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。
例如,下表 cinema:
±--------±----------±-------------±----------+
| id | movie | description | rating |
±--------±----------±-------------±----------+
| 1 | War | great 3D | 8.9 |
| 2 | Science | fiction | 8.5 |
| 3 | irish | boring | 6.2 |
| 4 | Ice song | Fantacy | 8.6 |
| 5 | House card| Interesting| 9.1 |
±--------±----------±-------------±----------+对于上面的例子,则正确的输出是为:
±--------±----------±-------------±----------+
| id | movie | description | rating |
±--------±----------±-------------±----------+
| 5 | House card| Interesting| 9.1 |
| 1 | War | great 3D | 8.9 |
±--------±----------±-------------±----------+来源:力扣(LeetCode)
链接:链接
where后面添加限制条件,描述不为无聊,使用and
加上id % 2 != 0
来确保为奇数,再按照评分降序排列即可。
Select id, movie, description, rating From cinema
Where description != 'boring' and (id % 2 != 0) Order By rating DESC;
627交换工资
力扣题目链接
给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。
注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。
例如:
id name sex salary 1 A m 2500 2 B f 1500 3 C m 5500 4 D f 500 运行你所编写的更新语句之后,将会得到以下表:
id name sex salary 1 A f 2500 2 B m 1500 3 C f 5500 4 D m 500 来源:力扣(LeetCode)
链接:链接
题目说明只使用一个update
语句,并且没有临时表,且不要编写select
。想到mysql有个case
来根据不同结果返回不同的值,在此时正好适用。修改sex
的值为(若是m
,返回f
;若是f
,返回m
)即可。
update salary s1 set sex = (
case s1.sex
when 'm' then 'f'
when 'f' then 'm'
end
);