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

SQL错误21000排查:子查询实现类VLOOKUP功能遇问题

问题原因及解决方法

错误21000的核心原因是:你SELECT列表里的子查询返回了多行结果,但这种标量子查询要求必须返回单个值(0行或1行)。当某个film_id在inventory表中对应多条记录时,子查询就会输出多个store_id,触发这个错误。

以下是几种适合你的子查询解决方案:

1. 只取每个影片对应的任意一个门店ID

用聚合函数(MIN/MAX)限制子查询返回单行,比如:

select 
e.film_id,
e.title, 
(select MIN(v.store_id) from inventory v where e.film_id = v.film_id) as store_id
from film e

这样即使一个影片对应多个门店,也只会返回最小的那个门店ID,不会报错。

2. 把同一个影片的所有门店ID合并成字符串

如果需要展示该影片关联的所有门店,可以用字符串聚合函数:

  • MySQL 版本:
select 
e.film_id,
e.title, 
(select GROUP_CONCAT(v.store_id SEPARATOR ', ') from inventory v where e.film_id = v.film_id) as store_ids
from film e
  • PostgreSQL/SQL Server 版本:
select 
e.film_id,
e.title, 
(select STRING_AGG(v.store_id::text, ', ') from inventory v where e.film_id = v.film_id) as store_ids
from film e

结果里store_ids会是类似1, 2这样的字符串,包含所有关联门店。

3. 实现和JOIN完全一致的多行结果

如果需要每个影片对应每一条库存记录(和LEFT JOIN效果相同),可以用LATERAL子查询(支持的数据库如PostgreSQL、SQL Server):

select 
e.film_id,
e.title, 
v.store_id
from film e
left join lateral (select store_id from inventory where film_id = e.film_id) v on true

这样没有库存的影片,store_id会显示为NULL,和LEFT JOIN结果一致。

内容的提问来源于stack exchange,提问作者mdc123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:32:37