postgresql SQLSTATE[22P02]:无效的文本表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13167186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQLSTATE[22P02]: Invalid text representation
提问by conradkleinespel
I'm using Postgresqland PHP 5.3.x with PDOto access the DB.
我使用带有 PDO 的Postgresql和PHP 5.3.x来访问数据库。
I have this the SQL query (stripped down version), with a placeholder for PDO to fill in:
我有这个 SQL 查询(精简版),并带有 PDO 的占位符来填写:
INSERT INTO t_articles (a_article_id) VALUES (?) RETURNING a_id
I want a_article_id
to be either a number, like 5
, or else it should be the result of the subquery:
我想a_article_id
是一个数字,比如5
,否则它应该是子查询的结果:
((SELECT max(a_article_id) FROM t_articles) + 1)
However, PDO says:
但是,PDO 说:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "(SELECT max(a_article_id) FROM t_articles) + 1"
And I've tried to set the subquery as the default value, but it is not allowed apparently:
我试图将子查询设置为默认值,但显然不允许:
ERROR: cannot use sub query in default expression
How can I insert the result of this sub query (or what can be done to achieve the same result)?
我怎样才能插入这个子查询的结果(或者可以做些什么来实现相同的结果)?
回答by mu is too short
You'd have to use INSERT...SELECT for that:
您必须为此使用 INSERT...SELECT :
insert into t_articles (a_article_id)
select max(a_article_id) + 1
from t_articles
returning id
Or if you don't need contiguous values for a_article_id
, use a sequencefor it:
或者,如果您不需要 的连续值,请为其a_article_id
使用序列:
Create a sequence, we'll call it
article_id_sequence
.-- Get the current max(a_article_id)+1 to use instead of FIRST_VAL below create sequence article_id_sequence start FIRST_VAL owned by t_articles.a_article_id;
Set the default value for
t_articles.a_article_id
tonextval('article_id_sequence')
.alter table t_articles alter column a_article_id set default nextval('article_id_sequence');
Use the default value when inserting:
insert into t_articles (a_article_id) values (default) returning id;
创建一个序列,我们称之为
article_id_sequence
。-- Get the current max(a_article_id)+1 to use instead of FIRST_VAL below create sequence article_id_sequence start FIRST_VAL owned by t_articles.a_article_id;
对于设置的默认值
t_articles.a_article_id
来nextval('article_id_sequence')
。alter table t_articles alter column a_article_id set default nextval('article_id_sequence');
插入时使用默认值:
insert into t_articles (a_article_id) values (default) returning id;