creating primary key based on date

前端 未结 4 580
南方客
南方客 2020-12-07 05:05

I am trying to create a unique ID for each record based on the date the record is created. Example, if the record is created today, I want the key to be 20101130XX where XX

相关标签:
4条回答
  • 2020-12-07 05:35

    This approach simply won't work because @Charles is true. You can't rely on a timestamp because there's a chance of duplicates (collision).

    Create a simple autoincrement id then save the timestamp too and you'll be happy.

    0 讨论(0)
  • 2020-12-07 05:37

    From dev.mysql.com: example-auto-increment.html

    For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.

    So, make 2 columns on the table, one dateEntered and one (auto_incremented) id, like this:

    CREATE TABLE yourTable (
        dateEntered DATE NOT NULL,
        id INT NOT NULL AUTO_INCREMENT,
        name CHAR(30) NOT NULL,
        PRIMARY KEY (dateEntered, id)
    ) ENGINE=MyISAM;
    

    If you don't use ISAM but InnoDB, I think you'll have to write your own trigger that implements this behaviour.

    0 讨论(0)
  • 2020-12-07 05:37

    What will you do if the number of entries per day exceeds 99? If you strongly want to use "20101130XX" index, I would recommend you use a compound key:

    CREATE TABLE `test` (
      `date` date NOT NULL,
      `id` tinyint(4) NOT NULL,
      `other_fields` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`date`,`id`)
    );
    
    0 讨论(0)
  • 2020-12-07 05:45

    Just use microtime() to be sure that there are no duplicate entries.

    function getUniqueID() {
      $mt = explode(' ', microtime());
      return $mt[1] . substr($mt[0], 2, 7);
      }
    

    P.S. You can always use lower precision then 7 digits.

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