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

          借用MySQL 的 auto_increment 特性可以產(chǎn)生唯一的可靠ID。

          表定義,關(guān)鍵在于auto_increment,和UNIQUE KEY的設(shè)置:

          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語法來獲取值,結(jié)合表定義的UNIQUE KEY,確保了一條記錄就可以滿足ID生成器的需求:

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

          以上方式中,通過MySQL的機(jī)制,可以確保此ID的唯一和自增,且適用于多并發(fā)的場景。官方對此的描述: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/

          相關(guān):

          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
          主站蜘蛛池模板: 泽库县| 广平县| 忻州市| 若尔盖县| 荥经县| 沅江市| 黑河市| 泊头市| 南溪县| 讷河市| 东台市| 蛟河市| 内黄县| 杭锦后旗| 靖边县| 邢台县| 中阳县| 中西区| 工布江达县| 怀仁县| 惠水县| 达州市| 德江县| 土默特右旗| 鄄城县| 衡南县| 龙口市| 襄垣县| 泸州市| 温宿县| 林芝县| 湖南省| 濮阳县| 双辽市| 娱乐| 永兴县| 麦盖提县| 西林县| 天门市| 喀喇沁旗| 三台县|