如何将uuid作为数字存储

如何将uuid作为数字存储

本文介绍了如何将uuid作为数字存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题的答案, UUID在MySQL中的性能答案建议将UUID存储为数字而不是字符串.我不太确定该怎么做.有人可以建议我吗?我的ruby代码如何处理呢?

Based on the answer of question, UUID performance in MySQL, the person who answers suggest to store UUID as a number and not as a string. I'm not so sure how it can be done. Anyone could suggest me something? How my ruby code deal with that?

推荐答案

如果我理解正确,那么您在主列中使用的是UUID吗?人们会说,常规(整数)主键会更快,但是还有另一种使用MySQL的阴暗面的方法.实际上,当需要索引时,MySQL使用二进制文件的速度比其他任何东西都要快.

If I understand correctly, you're using UUIDs in your primary column? People will say that a regular (integer) primary key will be faster , but there's another way using MySQL's dark side. In fact, MySQL is faster using binary than anything else when indexes are required.

由于UUID是128位并且以十六进制形式编写,因此非常容易加速和存储UUID.

Since UUID is 128 bits and is written as hexadecimal, it's very easy to speed up and store the UUID.

首先,以您的编程语言删除破折号

First, in your programming language remove the dashes

110E8400-E29B-11D4-A716-446655440000110E8400E29B11D4A716446655440000.

现在它是32个字符(就像MD5哈希一样,也可以使用).

Now it's 32 chars (like an MD5 hash, which this also works with).

由于MySQL中单个BINARY的大小为8位,所以BINARY(16)是UUID的大小(8 * 16 = 128).

Since a single BINARY in MySQL is 8 bits in size, BINARY(16) is the size of a UUID (8*16 = 128).

您可以使用:

INSERT INTO Table (FieldBin) VALUES (UNHEX("110E8400E29B11D4A716446655440000"))

并使用以下查询:

SELECT HEX(FieldBin) AS FieldBin FROM Table

现在,以您的编程语言,在9、14、19和24位置重新插入破折号以匹配原始UUID.如果位置总是不同,则可以将该信息存储在第二个字段中.

Now in your programming language, re-insert the dashes at the positions 9, 14, 19 and 24 to match your original UUID. If the positions are always different you could store that info in a second field.

完整示例:

CREATE TABLE  `test_table` (
    `field_binary` BINARY( 16 ) NULL ,
    PRIMARY KEY (  `field_binary` )
) ENGINE = INNODB ;

INSERT INTO  `test_table` (
    `field_binary`
)
VALUES (
    UNHEX(  '110E8400E29B11D4A716446655440000' )
);

SELECT HEX(field_binary) AS field_binary FROM `test_table`

如果要对任何十六进制字符串使用此技术,请始终对字段长度执行length / 2.因此,对于sha512,由于sha512编码的长度为128个字符,因此该字段为BINARY (64).

If you want to use this technique with any hex string, always do length / 2 for the field length. So for a sha512, the field would be BINARY (64) since a sha512 encoding is 128 characters long.

这篇关于如何将uuid作为数字存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:36