我有一个Postgres表,其中包含一个带有数值的字符串列.我需要将这些字符串转换为数字的数字,但我需要将两个NULL值以及空字符串解释为0.
我可以将空字符串转换为空值:
# select nullif('','');
nullif
--------
(1 row)
Run Code Online (Sandbox Code Playgroud)
我可以将null值转换为0:
# select coalesce(NULL,0);
coalesce
----------
0
(1 row)
Run Code Online (Sandbox Code Playgroud)
我可以将字符串转换为数字:
# select cast('3' as float);
float8
--------
3
(1 row)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试结合这些技术时,我会遇到错误:
# select cast( nullif( coalesce('',0), '') as float);
ERROR: invalid input syntax for integer: ""
LINE 1: select cast( nullif( coalesce('',0), '') as float);
# select coalesce(nullif('3',''),4) as hi;
ERROR: COALESCE types text and integer cannot be matched
LINE …Run Code Online (Sandbox Code Playgroud) 我有两列,id integer和version text.我试图将字符串转换version为整数,以便我可以选择id的最大(最新)版本.
但是,id商店本身的第一个实例为version.例:
id | version
---+--------
10 | '10'
Run Code Online (Sandbox Code Playgroud)
而不是:
id | version
---+--------
10 | '10-0'
Run Code Online (Sandbox Code Playgroud)
其他行遵循约定ID:10,版本:10-1.等等.
我怎么能做到这一点?我已经尝试split_part()并施展为int.但是,split_part(version, "-", 2)将返回看起来像空字符串的内容.我尝试使用a COALESCE(splitpart..., '0')无效,因为它试图读取字段索引2返回的空字段.
有时我需要在表中插入一些空值,或更新它们将值设置为NULL.
我这个不能做PostgreSQL文档在其他地方见过,但可以tricket使用默认值:
pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)
Run Code Online (Sandbox Code Playgroud)
ps:我知道在这个例子中我会得到相同的结果
pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')
Run Code Online (Sandbox Code Playgroud)
但问题来自准备好的陈述:
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, default)");
pg_exec($pgconn, 'insert_null_val', array('whatever'));
//this works, but
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', 'NULL'));
//insert into the table the string 'NULL'.
//instead using array('whatever', '') it assume the col_b as empty value, not NULL.
Run Code Online (Sandbox Code Playgroud)
更新查询也会出现同样的问题.
我认为有一个解决方案,因为pgmyadmin可以做到(或者看起来像它可以),并且我写的是php(我不认为它不会使用准备好的语句)
如果你想知道为什么我需要在我的表中使用空值,让我举一个例子(也许有一个比null值更好的方法):假设我有用户表,并且电子邮件col:这个可以为空,但是是唯一的索引.2空电子邮件是相同的并且违反了唯一约束,而2个NULL值不相等并且可以共存.