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

如何将两个返回不同结果的子查询输出合并为一个结果集?

合并两个SQL查询结果集的解决方案

要将两个返回相同列结构的查询结果合并为一个纵向的结果集,直接使用UNION ALL(或UNION)关键字即可。

修正后的合并SQL代码

注意:你的Q2原SQL逻辑是查询最短城市名,但输出结果对应最长城市名,这里已修正Q2的查询条件为max(length(city)):

-- 子查询1:获取最短名称的城市(按规则取第一条)
select
    city as "Column A",
    length(city) as "Column B"
from station
where length(city) = (select min(length(city)) from station)
order by length(city) asc, city asc 
limit 1

UNION ALL

-- 子查询2:获取最长名称的城市(按规则取第一条)
select
    city as "Column A",
    length(city) as "Column B"
from station
where length(city) = (select max(length(city)) from station)
order by length(city) asc, city asc 
limit 1;

关键说明

  • UNION ALL:直接合并两个结果集,保留所有行,效率更高(适合确定无重复行的场景)
  • UNION:会自动去除合并后结果中的重复行,但性能略低
  • 确保两个子查询返回的列数一致、数据类型匹配,同时通过别名统一列名,保证结果集结构符合预期

合并后的结果集

Column AColumn B
HHH3
bjhg4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:43:15