List:General Discussion« Previous MessageNext Message »
From:Michael Dykman Date:April 28 2009 11:39am
Subject:Re: How to generate unique primary key in MySQL?
View as plain text  
>>  I wish my id has the same length,auto_increment can do this?
>>
>
> I have a idear to generate unique primary key:
>
> select concat(cast(unix_timestamp() as char) , cast(substr(rand(),3,4) as
> char(4)));
>
> Is this ok? any good idear?

Your routine does not really guarantee uniqueness,  If you mean that
you want your keys to have the same display length, then the 36
character string produced by UUID() satisfies this.

Alternatively, and much simpler, is to use the auto_increment which
will give you the efficiency of an integer primary key,  When you want
to display it format it for display using LPAD.  ie.:

mysql> SELECT lpad(5,8,'0');
+---------------+
| lpad(5,8,'0') |
+---------------+
| 00000005      |
+---------------+


-- 
 - michael dykman
 - mdykman@stripped

 - All models are wrong.  Some models are useful.
Thread
How to generate unique primary key in MySQL?yuan edit28 Apr
  • Re: How to generate unique primary key in MySQL?yuan edit28 Apr
  • Re: How to generate unique primary key in MySQL?Michael Dykman28 Apr
  • Re: How to generate unique primary key in MySQL?Jim Lyons28 Apr
Re: How to generate unique primary key in MySQL?Michael Dykman28 Apr