当有一个AUTO INCREMENT字段

时间:2016-07-20 15:30:02

标签: mysql

我会谈到这一点。我有下表(MySQL 5.6.30)

CREATE TABLE `rankings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(255) DEFAULT NULL,
  `group_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `rankings_user_id_index` (`user_id`),
  KEY `rankings_group_id_index` (`group_id`)
) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=latin1 |

现在,在每次测试中,我都会删除记录并插入新记录,以便

mysql> SELECT * FROM rankings WHERE user_id = 'hermione' and group_id = 'enchantments';
+-----+----------+--------------+
| id  | user_id  | group_id     |
+-----+----------+--------------+
| 122 | hermione | enchantments |
| 123 | hermione | enchantments |
+-----+----------+--------------+
2 rows in set (0.00 sec)

但是,检查总计数时测试失败(出于分页目的,我只检索部分记录)

mysql> SELECT count(*) FROM rankings WHERE user_id = 'hermione' and group_id = 'enchantments';
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

这是一种非常奇怪的行为......再多挖一点,我观察到了:

  • 如果我不使用自动增量字段,一切正常。

  • 如果我手动插入更多记录,在某些时候第二个查询会按预期开始工作(缓存问题?)。

错误和正确结果的explain query(按此顺序)如下:

// WRONG
{
  select_type: SIMPLE,
  type: ref,
  possible_keys: rankings_user_id_index,rankings_group_id_index,
  key: rankings_user_id_index,
  ref: const,
  rows: 10
  extra: Using index condition; Using where
}


// RIGHT
{
  select_type: SIMPLE,
  type: index_merge,
  possible_keys: rankings_user_id_index,rankings_group_id_index,
  key: rankings_user_id_index,rankings_medgroup_id_index,
  ref: NULL,
  rows: 2
  extra: Using intersect(rankings_user_id_index,rankings_group_id_index); Using where; Using index
}

我不了解MySQL的内部结构,但我认为它试图以某种方式优化计数。但是,它失败了(至少在测试环境中,表记录被删除并在每个测试用例之前重新创建)。我错过了一些清洁步骤吗? MySQL的计数缓存是否会以这种方式工作?

谢谢

0 个答案:

没有答案