posts - 495,comments - 227,trackbacks - 0
          http://lztian.com/blog/5921.html

          借用MySQL 的 auto_increment 特性可以產生唯一的可靠ID。

          表定義,關鍵在于auto_increment,和UNIQUE KEY的設置:

          1
          2
          3
          4
          5
          6
          CREATE TABLE `Tickets64` (
            `id` bigint(20) unsigned NOT NULL auto_increment,
            `stub` char(1) NOT NULL default '',
            PRIMARY KEY  (`id`),
            UNIQUE KEY `stub` (`stub`)
          ) ENGINE=MyISAM

          需要使用時,巧用replace into語法來獲取值,結合表定義的UNIQUE KEY,確保了一條記錄就可以滿足ID生成器的需求:

          1
          2
          REPLACE INTO Tickets64 (stub) VALUES ('a');
          SELECT LAST_INSERT_ID();

          以上方式中,通過MySQL的機制,可以確保此ID的唯一和自增,且適用于多并發的場景。官方對此的描述:https://dev.mysql.com/doc/refman/5.0/en/information-functions.html

          1
          2
          3
          It is multi-user safe because multiple clients can issue the UPDATE statement and
          get their own sequence value with the SELECT statement (or mysql_insert_id()),
          without affecting or being affected by other clients that generate their own sequence values.

          需要注意的是,若client采用PHP,則不能使用mysql_insert_id()獲取ID,原因見《mysql_insert_id() 在bigint型AI字段遇到的問題》:http://kaifage.com/notes/99/mysql-insert-id-issue- with-bigint-ai-field.html。

          Flickr 采取了此方案: http://code.flickr.net/2010/02/08/ticket-servers-distributed-unique-primary-keys-on-the-cheap/

          相關:

          http://www.zhihu.com/question/30674667

          http://my.oschina.net/u/142836/blog/174465

          posted on 2016-06-28 18:48 SIMONE 閱讀(1348) 評論(0)  編輯  收藏 所屬分類: mysql
          主站蜘蛛池模板: 瑞昌市| 西安市| 肥城市| 镇沅| 登封市| 淮南市| 绥阳县| 广饶县| 姚安县| 永清县| 光泽县| 肇庆市| 西宁市| 伊吾县| 闵行区| 二连浩特市| 南木林县| 五峰| 新和县| 景东| 哈密市| 古丈县| 江永县| 平和县| 前郭尔| 宁乡县| 祁门县| 泾川县| 铅山县| 团风县| 报价| 隆德县| 呼玛县| 龙南县| 满城县| 浦北县| 阿克苏市| 建湖县| 凤凰县| 定安县| 腾冲县|