DROP TABLE IF EXISTS `auto_user_id`; CREATE TABLE `auto_user_id` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `max_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '占位字段', `create_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', PRIMARY KEY (`id`), UNIQUE KEY `auto_max_id_uindex` (`max_id`) ) ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='自动生成 id';
DROP TABLE IF EXISTS `auto_article_id`; CREATE TABLE `auto_article_id` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `max_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '占位字段', `create_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', PRIMARY KEY (`id`), UNIQUE KEY `auto_max_id_uindex` (`max_id`) ) ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='自动生成 id';
DROP TABLE IF EXISTS `auto_id`; CREATE TABLE `auto_id` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `max_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '占位字段', `create_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间', PRIMARY KEY (`id`), UNIQUE KEY `auto_max_id_uindex` (`max_id`) ) ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='自动生成 id';
DROP FUNCTION IF EXISTS `func_gen_auto_id`; DELIMITER $$ CREATE FUNCTION `func_gen_auto_id`(shard_seed BIGINT, item_name VARCHAR(10)) RETURNS BIGINT(20) BEGIN DECLARE shard_offset INT; DECLARE item_offset INT; DECLARE item_seed INT;
CASE item_name WHEN 'user' THEN SET item_seed = 1; WHEN 'article' THEN SET item_seed = 2; ELSE SET item_seed = 0; END CASE;
SET shard_id = (SELECT shard_seed << shard_offset); SET item_type = (SELECT item_seed << item_offset);
CASE item_name WHEN 'user' THEN replace INTO auto_user_id (`max_id`) VALUES (1); WHEN 'article' THEN replace INTO auto_article_id (`max_id`) VALUES (1); ELSE replace INTO auto_id (`max_id`) VALUES (1); END CASE;
SET last_insert_id = (SELECT last_insert_id());
SET final_id = (SELECT shard_id + item_type + last_insert_id); RETURN final_id; END $$ DELIMITER ;