有时我需要在表中插入一些空值,或者更新它们,将值设置为 NULL。
我在 Postgres 文档中的某处读到这无法完成,但可以用默认值欺骗:
pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)
我知道在这个例子中我会得到相同的结果:
pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')
但是问题出在准备好的语句上:
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.
同样的问题也适用于更新语句。
我认为有一个解决方案,因为 pgmyadmin 可以做到(或者看起来可以)。
如果你想知道为什么我需要在我的表中使用空值,让我举一个例子(也许有比空值更好的方法?):
假设我有一个users
包含一列的表,该email
列可以为空,但具有唯一索引。2 个空邮件相等,违反唯一约束,而 2 个NULL值不相等,可以共存。