我正在尝试运行这样的查询
select * from mytable where to_number(minutesintext, '9999') >= 10;
expected result:
col1 | col2 | col3 | minutesintext
-------------------------------------
a | b | c | 11
f | g | e | 98
但是我经常遇到这个错误:
[22P02] ERROR: invalid input syntax for type numeric: " "
我已经看到 to_number() 的示例用法都是:
select to_number('45', '9999');
results in:
45
并且似乎找不到使用 to_number() 函数作为条件子句的一部分的示例。 我究竟做错了什么?以及如何在查询期间将整数(存储为文本)转换为数字时查询所有行。
*更改列的数据类型是不可能的,因为它需要存储为文本。
我在本地环境中使用 PostgreSQL 13.1,在远程环境中使用 PostgreSQL 11
感谢任何帮助! :)
最佳答案
通常这有效:demo:db<>fiddle
但是,您的错误消息显示:您似乎有一条记录,其中有一个空字符串,这自然不能被解释为数字。
为了避免这种情况,您可以添加一些修复逻辑,例如添加 NULLIF()
函数:
select * from mytable
where to_number(
NULLIF(minutesintext, ' '), '9999'
) >= 10;
如果不需要解析特定的数字格式,只需将(转义的)文本转换为 int
类型:
select * from mytable
where NULLIF(minutesintext, ' ')::int >= 10;
关于postgresql - 如何在psql查询中将文本数字转换为整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66675434/