简体   繁体   中英

How to convert a string to a unique number?

I have a table like this:

// viewed
+----+------------------+
| id |  username_or_ip  |
+----+------------------+

As you see, username_or_ip columns keeps username or ip . And its type is INT(11) UNSIGNED . I store IP like this:

INSERT table(ip) VALUES (INET_ATON('192.168.0.1'));

// It will be saved like this: ip = 3232235521

Well, I want to know, is there any approach for converting a string like Sajad to a unique number? (because as I said, username_or_ip just accepts digit values)

int(11) is a 32-bit data type. As such it's just enough to hold an ipv4 address. Your question points that out.

To reversibly convert an arbitary string to a 32-bit data type is difficult: it simply lacks the information storage capacity.

You could use a lookup table for the purpose. Many languages, including php 5.4+, support that using an process called "interning." https://en.wikipedia.org/wiki/String_interning

Or you could build yourself a lookup table in a MySQL table. Its columns would be an id column and a value column. You'd intern each new text string by creating row for it with a unique id value, then use that value.

Your intuition about the slowness of looking up varchar(255) or similar values in MySQL is reasonable. But, with respect, it is not correct. Properly indexed, tables with that kind of data in them are very fast to search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM