← 中文资源

简体中文版本

标量子查询最多返回一行

标量子查询用在表达式位置时最多允许一行:主键等值查询天然安全,按非唯一列过滤一旦命中两行整条语句直接报错,必须加 LIMIT 1。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 teams、players。 把语句拆开看,工作部件是:WHERE 按条件筛出这条语句真正触碰的行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;要求子行必须指向父表的 REFERENCES 外键守卫。

常见问题

它引用了哪些表或 CTE?

teams、players。

核心语句

SELECT player_id,
       (SELECT region FROM teams t WHERE t.team_id = p.team_id) AS region
FROM players p;
CREATE TABLE players (
    player_id int PRIMARY KEY,
    team_id   int NOT NULL REFERENCES teams(team_id)
);
CREATE TABLE teams (
    team_id int PRIMARY KEY,
    region  text NOT NULL
);

代码示例

-- a scalar subquery sits in expression position and returns at most one row
CREATE TABLE teams (
    team_id int PRIMARY KEY,
    region  text NOT NULL
);
INSERT INTO teams VALUES (1, 'east'), (2, 'east'), (3, 'west');

CREATE TABLE players (
    player_id int PRIMARY KEY,
    team_id   int NOT NULL REFERENCES teams(team_id)
);
INSERT INTO players VALUES (10, 1), (11, 3);

-- ok: looked up by primary key, naturally at most one row
SELECT player_id,
       (SELECT region FROM teams t WHERE t.team_id = p.team_id) AS region
FROM players p;

-- crash: region is not unique, so two rows for the same value raise a cardinality error for the whole statement
-- ERROR: more than one row returned by a subquery used as an expression
-- SELECT player_id,
--        (SELECT region FROM teams WHERE region = 'east') AS region
-- FROM players;