You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL 9.6无关联键时,非JOIN/CASE的跨表查询需求

PostgreSQL 9.6 无CASE/JOIN的成绩等级匹配查询

表结构与数据

Person表

idnamescore
1apple8
4berry9
6cat5
7dog2

Grade表

grademin_scoremax_score
D02
C35
B68
A910

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;

期望输出

namegrade
appleB
berryA
catC
dogD

解决方案

可以在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:35:05