mysql_insert_id或类似的东西返回最后一个mysql UUID() [英] mysql_insert_id or something like that to return last mysql UUID()
问题描述
如何返回最后生成的UUID()(主键)-是否有类似mysql_insert_id的东西?
How do you return the last generated UUID() (primary key) - is there something like mysql_insert_id for that?
表uuidtable
:
primary key: uuid uuid()
id_u (index): integer
多个id_u与主键uuid()匹配
multiple id_u matched with a primary key uuid()
插入:insert into uuidtable (uuid,id_u) values (uuid(),id)
当然,其中id是一个数字,而uuid使用
where id is a number, of course, and uuid is escaped with
uuid
推荐答案
为自己编写一个触发器,如下所示:
Write yourself a trigger like so:
CREATE TRIGGER ai_uuidtable
AFTER INSERT ON uuidtable
FOR EACH ROW
SET @last_uuid = NEW.uuid;
在插入之后:
SELECT @last_uuid
MySQL的用户定义变量是特定于连接的,因此您不必担心获取另一个连接的@last_uuid
.
MySQL's user-defined variables are connection-specific, so you don't have to worry about getting another connection's @last_uuid
.
一个关注点:如果您使用uuid作为键,则为了使其发挥最大性能,应将其存储为16字节的binary
字段,而不是36字节的char
场地.如果您确实要使用MySQL的UUID()
算法,请去除连字符并UNHEX()
One point of concern: If you're using the uuid as a key, in order for it to be maximally performant, it should be stored as a 16-byte binary
field and not a 36-byte char
field. If you really want to use MySQL's UUID()
algorithm, strip out the hyphens and UNHEX()
it:
UNHEX( REPLACE( UUID(), '-', '' ) )
此外:PostgreSQL实际上具有UUID数据类型(但没有内置的UUID()
函数),这意味着您不必重新HEX()
字段即可避免在终端中获取二进制垃圾在SELECT
.
Aside: PostgreSQL actually has a UUID data type (but no built-in UUID()
function), which just means you don't have to re-HEX()
the field in order to avoid getting binary garbage in your terminal on SELECT
.
这篇关于mysql_insert_id或类似的东西返回最后一个mysql UUID()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!