Storing MySQL GUID/UUIDs

后端 未结 2 389
别跟我提以往
别跟我提以往 2020-12-04 12:25

This is the best way I could come up with to convert a MySQL GUID/UUID generated by UUID() to a binary(16):

UNHEX(REPLACE(UUID(),\'-\',\'\'))
相关标签:
2条回答
  • 2020-12-04 12:58

    From MySQL 8.0 and above you could use UUID_TO_BIN:

    UUID_TO_BIN(string_uuid), UUID_TO_BIN(string_uuid, swap_flag)

    Converts a string UUID to a binary UUID and returns the result. (The IS_UUID() function description lists the permitted string UUID formats.) The return binary UUID is a VARBINARY(16) value.

    CREATE TABLE t (id binary(16) PRIMARY KEY);
     
    INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true));
    INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true));
    INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true));
    
    SELECT *, BIN_TO_UUID(id) FROM t;
    

    DB-Fiddle.com Demo

    0 讨论(0)
  • 2020-12-04 13:16

    Not many implications. It will slow down the queries a little, but you will hardly notice it.

    UNIQUEIDENTIFIER is stored as 16-byte binary internally anyway.

    If you are going to load the binary into a client and parse it there, note the bit order, it may have other string representation than the initial NEWID().

    Oracle's SYS_GUID() function is prone to this issue, converting it to a string gives different results on client and on server.

    0 讨论(0)
提交回复
热议问题