"插入表A(col1,col2)之后的mysql auto_increment错误选择col3,col4来自tableB"

时间:2016-09-09 06:39:21

标签: mysql sql-server

当我从tableB向tableA插入一些行时,它像往常一样工作。 auto_increment键' id'插入的行是正常的,但下一个auto_increment' id'是一个例外。在我的例子中,SQL的结果表明受影响的行总数是5504,插入的实际行是5504,但是下一个“id”#39;是8192应该是5505。

我的表格结构如下:

-- ----------------------------
-- Table structure for t_ds
-- ----------------------------
DROP TABLE IF EXISTS `t_ds`;
CREATE TABLE `t_ds` (
  `id` bigint(64) NOT NULL AUTO_INCREMENT,
  `deviceId` varchar(50) DEFAULT NULL,
  `eventId` varchar(50) DEFAULT NULL,
  `eventTime` bigint(64) DEFAULT NULL,
  `logInfoId` bigint(64) DEFAULT NULL,
  `statusCode` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_ds` (`deviceId`,`eventId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

和SQL插入语句:

INSERT INTO t_ds(deviceId, eventId, eventTime, logInfoId, statusCode)
SELECT deviceId, eventId, eventTime, id, statusCode FROM t_loginfo
WHERE (deviceId, eventId, eventTime) in (
    SELECT
        deviceId, eventId, MAX(eventTime)
    FROM
        t_loginfo
    GROUP BY deviceId, eventId
)
GROUP BY deviceId, eventId;

我不知道增量键的原因是什么'一直是一个奇怪的数字,所以我做了一些尝试找到原因。首先,我删除了表格' t_ds' ,重建它并附加sql'限制*,1'在上面的sql insert语句中,逐行插入行,奇怪的数字消失,它是正常的。

所以我做了一些实验。

1. delete table 't_ds' , rebuild it.
2. run the SQL insert statement with limit *,*.

结果:

limit 0,1: insert 1 row, total rows is 1, the last id is 1, the next id is 2;
limit 1,2: insert 2 row, total rows is 3, the last id is 3, the next id is 5;
limit 3,3: insert 3 row, total rows is 6, the last id is 7, the next id is 8;
limit 6,4: insert 4 row, total rows is 10, the last id is 11, the next id is 15;
limit 10,5: insert 5 row, total rows is 15, the last id is 19, the next id is 22;

id的序列:

1 2 3 5 6 7 8 9 10 11 15 16 17 18 19

另一个奇怪的情况是插入行的数量是5000+还是6000+,两个下一个id都是8192。

1 个答案:

答案 0 :(得分:0)

这是一个非常常见的问题。重新启动SQL Server时通常会发生这种情况。当我们在开发服务器中时,会出现此类问题。它很少发生在生产服务器上。因为生产服务器不经常重启。