PostgreSQL 9.6无关联键时,非JOIN/CASE的跨表查询需求
PostgreSQL 9.6 无CASE/JOIN的成绩等级匹配查询
表结构与数据
Person表
| id | name | score |
|---|---|---|
| 1 | apple | 8 |
| 4 | berry | 9 |
| 6 | cat | 5 |
| 7 | dog | 2 |
Grade表
| grade | min_score | max_score |
|---|---|---|
| D | 0 | 2 |
| C | 3 | 5 |
| B | 6 | 8 |
| A | 9 | 10 |
DDL与DML语句
create table Person (ID int, name varchar, score int); create table Grade (grade varchar, min_score int, max_score int); insert into Person values (1, 'apple', 8), (4, 'berry', 9), (6, 'cat', 5), (7, 'dog', 2); insert into Grade values ('D', 0, 2), ('C', 3, 5), ('B', 6, 8), ('A', 9, 10);
需求与问题
需要编写一条不使用CASE或JOIN语句的SQL查询,输出每个人的name对应的grade字段。尝试的以下查询无法正常运行:
select * from Grade g where (select score from Person) between g.min_score and g.max_score;
期望输出
| name | grade |
|---|---|
| apple | B |
| berry | A |
| cat | C |
| dog | D |
解决方案
可以在SELECT子句中使用相关子查询实现需求,SQL语句如下:
select p.name, (select g.grade from Grade g where p.score between g.min_score and g.max_score) as grade from Person p;
说明
Grade表中的分数区间互斥且覆盖所有可能的分数范围,针对Person表的每条记录,子查询会精准匹配到唯一对应的等级,符合标量子查询的返回要求,因此可以得到期望结果。
内容的提问来源于stack exchange,提问作者Liu Yu
相关产品推荐
相关产品推荐

