首页 > 解决方案 > 数字=字符变化:基于 postgres 数据库的操作符不存在

问题描述

我有这样的查询:

Select office_name, ofc_code 
from table1 
where ofc_code in (select ofc_institution from table2 where id ='2')

如果我运行它,我会得到一个错误:

Operator does not exist:numeric = character varying
Hint : no operator matches the given name and argument types

在上面的查询中:ofc_code是数字并且ofc_institution是一个不同的字符

标签: sqlpostgresql

解决方案


不要将苹果与橙子进行比较。'2'是一个字符串值,2是一个数字。

ofc_institution如果您确定它只包含数字,您还需要转换为数字(那么问题是:到底为什么要将数字存储在varchar列中?):

Select office_name, ofc_code 
from table1 
where ofc_code in (select ofc_institution::numeric
                   from table2 
                   where id = 2);

如果您不能确定它ofc_institution始终是一个数字,那么将其ofc_code转换为一个字符串 - 但这会引出一个问题,您为什么要比较这些列的开头:

Select office_name, ofc_code 
from table1 
where ofc_code::varchar in (select ofc_institution
                            from table2 
                            where id = 2);

推荐阅读