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

PostgreSQL中UNION操作出现integer与text类型不匹配错误求助

问题原因分析

错误UNION types integer and text cannot be matched的核心是:UNION操作要求上下两个查询的对应列必须具有完全一致的数据类型。

看你的SQL:

  • 第一个查询中price5列是整数类型(固定值0)
  • 第二个查询中price5列是文本类型(返回'yes'或'no')

这两个列类型不兼容,导致PostgreSQL无法执行UNION合并。

另外你的原SQL逻辑存在冗余:两个查询都按product_name, price分组,本质是对同一批分组数据做两次判断再合并结果,完全没必要,反而会导致重复数据(即便UNION去重后也不符合预期)。

修正方案(符合你的需求)

根据你描述的“当sum(price)小于100时显示'no',否则显示'yes'”的需求,直接在单个查询中完成所有逻辑即可,不需要UNION:

select 
  product_name,
  0::integer as price1,
  0::integer as price2,
  0::integer as price3,
  case when sum(price) > 100 then 1 else 0 end as price4,
  case when sum(price) < 100 then 'no' else 'yes' end as price5
from sales_1
group by product_name, price;

如果你的业务逻辑确实需要保留UNION结构(比如分不同分支返回不同列值),必须确保对应列类型一致,修改如下:

-- 第一个查询:price5改为文本类型,与第二个查询匹配
select 
  product_name,
  0::integer as price1,
  0::integer as price2,
  0::integer as price3,
  case when sum(price) > 100 then 1 else 0 end as price4,
  '0'::text as price5
from sales_1
group by product_name, price

union 

select 
  product_name,
  0::integer as price1,
  0::integer as price2,
  0::integer as price3,
  0::integer as price4,
  case when sum(price) < 100 then 'no' else 'yes' end as price5
from sales_1
group by product_name, price;
额外提示

注意你当前的group by product_name, price逻辑:因为price是分组字段,sum(price)的结果其实等于单个price值(每个分组里只有一条price记录)。如果你的意图是按product_name分组计算总价格,应该把price从group by中移除:

select 
  product_name,
  0::integer as price1,
  0::integer as price2,
  0::integer as price3,
  case when sum(price) > 100 then 1 else 0 end as price4,
  case when sum(price) < 100 then 'no' else 'yes' end as price5
from sales_1
group by product_name;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:10:19