【leetcode两题选手】MySQL类题目(七)

时间:2022-07-23
本文章向大家介绍【leetcode两题选手】MySQL类题目(七),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题一:最大的国家

这里有张 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      |
+--------------+-------------+--------------+

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/big-countries 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

这题其实很简单的。

select name,population,area
from World
where population>25000000 or area>3000000;

题二:超过五名学生的课

有一个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: 学生在每个课中不应被重复计算。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/classes-more-than-5-students 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

本来也是个简单题,但是吧,遇到了有的学生一个课选几次的情况。

SELECT
    class
FROM
    courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5
;

收获

方法:使用 GROUP BY 子句和子查询 先统计每门课程的学生数量,再从中选择超过 5 名学生的课程。 使用 GROUP BY 和 COUNT 获得每门课程的学生数量。

SELECT
    class, COUNT(DISTINCT student)
FROM
    courses
GROUP BY class
;

注:使用 DISTINCT 防止在同一门课中学生被重复计算。

| class    | COUNT(student) |
|----------|----------------|
| Biology  | 1              |
| Computer | 1              |
| English  | 1              |
| Math     | 6              |

使用上面查询结果的临时表进行子查询,筛选学生数量超过 5 的课程。

SELECT
    class
FROM
    (SELECT
        class, COUNT(DISTINCT student) AS num
    FROM
        courses
    GROUP BY class) AS temp_table
WHERE
    num >= 5
;

> 作者:LeetCode
> 链接:https://leetcode-cn.com/problems/classes-more-than-5-students/solution/chao-guo-5ming-xue-sheng-de-ke-by-leetcode/
> 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。