postgresql -- Curval 不起作用,使用 PHP PDO
所以我尝试通过 PHP 的 PDO (我不认为这应该是问题)在这里运行一些 SQL,如下所示:
INSERT INTO example (
d_id,
s_id
)
VALUES (
currval('d_id_seq'),
currval('s_id_seq')
);
我有两个名为 d_id_seq 和 s_id_sec 的序列(假设我有一个名为 d
的表和一个名为 s
的表,这个序列是一个名为 ID 和 serial
类型的列)。
现在,显然我做错了,因为我收到有关此会话中未使用的序列的错误:
对象不处于先决条件状态:7 错误:序列“d_id_seq”的 currval 尚未在此会话中定义
那么,我应该如何写呢?
So I'm trying to run some SQL here through PHP's PDO (which I don't believe should be the problem) like such:
INSERT INTO example (
d_id,
s_id
)
VALUES (
currval('d_id_seq'),
currval('s_id_seq')
);
I have two sequences called d_id_seq
and s_id_sec
(lets pretend I have a table named d
and a table named s
, and this sequence is a column called ID and serial
type).
Now, obviously I'm doing this wrong, as I get an error about the sequence not being used in this session:
Object not in prerequisite state: 7 ERROR: currval of sequence "d_id_seq" is not yet defined in this session
So, how should I write this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该错误意味着您没有“使用”此会话中的序列(postgres 连接)。例如,您没有对表 d 执行任何 INSERT。
也许您的代码中有错误并在每次查询后重新连接到 postgres?
更方便的方法是在 INSERT 上使用 INSERT RETURNING。然后你就得到了 id。
The error means you did not "use" the sequence in this session (postgres connection). For instance you did not do any INSERTs on the table d.
Perhaps you have a bug in your code and reconnect to postgres after each query ?
A more convenient way to do it is to use INSERT RETURNING on your INSERTs. Then you get the ids.
问题可以通过以下命令解决:
请注意,我使用的是 PostgreSQL 9.1.9,我不知道其他或更旧的版本。
Problem can be solved via the following command:
Note that I'm using PostgreSQL 9.1.9, I do not know about other or older versions.
来自精细手册:
您可以使用 currval 获取从当前会话中的序列中提取的最后一个值。通常的模式是执行使用序列的 INSERT,然后调用 currval 来确定 INSERT 使用的值。如果您尚未在当前会话中使用相关序列调用
nextval
,则currval
不会返回任何内容。也许您实际上正在寻找
select max(id) from d
和select max(id) from s
:或者您可能需要包装您的
d 和
s
插入存储过程中,该存储过程负责同时插入所有三个表。From the fine manual:
You use
currval
to get the last value that was pulled out of the sequence in the current session. The usual pattern is to do an INSERT that uses a sequence and then you callcurrval
to figure out what value the INSERT used. If you haven't callednextval
with the sequence in question in the current session then there is nothing forcurrval
to return.Maybe you're actually looking for
select max(id) from d
andselect max(id) from s
:Or maybe you need to wrap your
d
ands
inserts in a stored procedure that takes care of inserting in all three tables at once.