postgresql 的 mysql_insert_id 替代品
PostgreSQL 的 mysql_insert_id()
php 函数有替代方案吗? 大多数框架通过查找 ID 中使用的序列的当前值来部分解决问题。 但是,有时主键不是串行列......
is there an alternative for mysql_insert_id()
php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 php.net:
这应该始终提供唯一的密钥,因为从数据库检索到的密钥将永远不会再次检索。
From php.net:
This should always provide unique key, because key retrieved from database will be never retrieved again.
查看 INSERT 语句的 RETURNING 可选子句。 (链接到官方 PostgreSQL 文档)
但基本上,您可以这样做:
并且 INSERT 语句本身返回受影响行的 id(或您指定的任何表达式)。
Check out the RETURNING optional clause for an INSERT statement. (Link to official PostgreSQL documentation)
But basically, you do:
and the INSERT statement itself returns the id (or whatever expression you specify) of the affected row.
您还可以使用:
您必须在 pg_fetch_result 中指定您要查找的行号和字段名称,这是获取您需要的数据的更精确的方法,但我不知道这是否有效查询的性能会受到一些影响。 请记住,此方法适用于 PostgreSQL 8.2 及更高版本。
You also can use:
You have to specify in pg_fetch_result the number of the row and the name of the field that you are looking for, this is a more precise way to get the data that you need, but I don't know if this has some penalty in the performance of the query. Remember that this method is for PostgreSQL versions 8.2 and up.
从 PostgreSQL 的角度来看,在伪代码中:
pg_last_oid()
仅适用于有 OID 的情况。 自 PostgreSQL 8.1 起,OID 默认处于关闭状态。因此,根据您使用的 PostgreSQL 版本,您应该选择上述方法之一。 当然,理想情况下,使用数据库抽象库来抽象上述内容。 否则,在低级代码中,它看起来像:
方法一:INSERT... RETURNING
方法二:INSERT; lastval()
方法三:nextval(); INSERT
最安全的选择是第三种方法,但它很笨拙。 最干净的是第一个,但您需要运行最近的 PostgreSQL。 不过,大多数数据库抽象库尚未使用第一种方法。
From the PostgreSQL point of view, in pseudo-code:
pg_last_oid()
only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1.So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like:
Method one: INSERT... RETURNING
Method two: INSERT; lastval()
Method three: nextval(); INSERT
The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though.