mysql手動取得自增主鍵的方法:透過建立預存程序外加函數的方式維護一張sequences表來取得數據,程式碼為【last_number = last_number increment_by】。
mysql手動取得自增主鍵的方法:
透過建立儲存程序外加函數的方式維護一張sequences表來取得資料(一次解決終身受用)。
可以指定每次自增的大小,以及初始數。
select nextval('TESTDATA') AS batchId CREATE DEFINER=`admin`@`%` FUNCTION `nextval`(seq_name VARCHAR (50)) RETURNS bigint(20) BEGIN UPDATE SEQUENCES SET last_number = last_number + increment_by WHERE sequence_name = seq_name; RETURN currval (seq_name); END;
CREATE DEFINER=`admin`@`%` FUNCTION `currval`(seq_name VARCHAR (50)) RETURNS bigint(20) NO SQL BEGIN SELECT last_number INTO @VALUE FROM SEQUENCES WHERE sequence_name = seq_name; RETURN @VALUE; END;
DROP TABLE IF EXISTS `sequences`; CREATE TABLE `sequences` ( `sequence_owner` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `sequence_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, `min_value` bigint(20) NULL DEFAULT 1, `max_value` bigint(20) NULL DEFAULT NULL, `increment_by` bigint(20) NOT NULL DEFAULT 1, `cycle_flag` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `order_flag` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `cache_size` bigint(20) NOT NULL, `last_number` bigint(20) NOT NULL, PRIMARY KEY (`sequence_name`) USING BTREE, UNIQUE INDEX `sel`(`sequence_owner`, `sequence_name`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact; -- ---------------------------- -- Records of sequences -- ---------------------------- INSERT INTO `sequences` VALUES ('SCM', 'TESTDATA', 1, 9999999999, 1, 'N', 'Y', 20, 0); INSERT INTO `sequences` VALUES ('SCM', 'SEQ', 1, 9999999999, 1, 'N', 'N', 20, 0); SET FOREIGN_KEY_CHECKS = 1;
#更多相關免費學習推薦:mysql教學(影片)
以上是MySql如何手動取得自增主鍵的詳細內容。更多資訊請關注PHP中文網其他相關文章!