- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
描述
请编写 SQL 语句,使用内联视图,查询最年长且教师国籍为 USA 的信息。
表定义:teachers(教师表)
| 列名 | 类型 | 注释 |
|---|---|---|
| id | int unsigned | 主键 |
| name | varchar | 教师姓名 |
| varchar | 教师邮箱 | |
| age | int | 教师年龄 |
| country | varchar | 教师国籍 |
**
- 查询返回列名需要与样例输出的列名大小写一致。
- 最年长且国籍是美国的教师可能不止一位。
- 如果输入数据中存在教师年龄或教师国籍信息为 NULL,则跳过该数据。
- 如果查询不到结果,就什么都不返回。
样例
样例一:
表内容:teachers
| id | name | age | country | |
|---|---|---|---|---|
| 1 | Eastern Heretic | eastern.heretic@gmail.com | 20 | UK |
| 2 | Northern Beggar | northern.beggar@qq.com | 21 | CN |
| 3 | Western Venom | western.venom@163.com | 28 | USA |
| 4 | Southern Emperor | southern.emperor@qq.com | 21 | JP |
| 5 | Linghu Chong | NULL | 18 | CN |
在运行你的 SQL 语句之后,表应返回:
| id | name | student_count | created_at | teacher_id |
|---|---|---|---|---|
| 3 | Western Venom | western.venom@163.com | 28 | USA |
样例二:
表内容:teachers
| id | name | age | country | |
|---|---|---|---|---|
| 1 | Eastern Heretic | eastern.heretic@gmail.com | 20 | UK |
| 2 | Northern Beggar | northern.beggar@qq.com | 21 | CN |
| 4 | Southern Emperor | southern.emperor@qq.com | 21 | JP |
| 5 | Linghu Chong | NULL | 18 | CN |
在运行你的 SQL 语句之后,表应返回:
| id | name | student_count | created_at | teacher_id |
|---|
因为输入样例中没有符合条件的数据,所以这里只展示了标题,没有数据。
题解
什么是内联视图:
内联视图是SQL语言(结构化查询语言)中三种主要视图(标准视图、内联视图、物化视图)中的一种。内联视图是一种临时视图,不存储到数据字典中。它和标准视图在使用过程中的主要区别是,不需要在进行SELECT查询语句前进行视图的创建。
先根据 country = 'USA'找到最大的年纪,然后再根据最大的年纪找到老师
select *
from teachers
where age = (
select max(age)
from teachers
where country = 'USA'
) and country = "USA";