强制'替换为'以使用某个索引

时间:2010-04-12 10:10:17

标签: mysql

我有一个包含3行的MySQL(5.0)表,它被视为组合的唯一索引:

CREATE TABLE `test`.`table_a` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `field1` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
  `field2` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
  `field3` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`Id`),
  INDEX `IdxUnqiue` (`field1`(5),`field2`(5),`field3`(5))
) ENGINE=MyISAM;

此表格应填入REPLACE INTO查询:

REPLACE INTO
    table_a
(
    Field1,
    Field2,
    Field3
)
VALUES
(
    "Test1",
    "Test2",
    "Test3"
)

我想看到的行为是这个查询总是覆盖先前插入的行,因为IdxUnique是......啊,触发了。但不幸的是,仍然存在主要指标似乎已经开始并且总是插入一个新行。

我得到了什么:

Query was executed 3 times:

+---Id---+---Field1---+---Field2---+---Field3---+
| 1      | Test1      | Test2      | Test2      |
| 2      | Test1      | Test2      | Test2      |
| 3      | Test1      | Test2      | Test2      |
+--------+------------+------------+------------+

我想要的是什么:

Query was executed 3 times:

+---Id---+---Field1---+---Field2---+---Field3---+
| 3      | Test1      | Test2      | Test2      |
+--------+------------+------------+------------+

那么,我可以告诉REPLACE INTO只使用某个指数,还是考虑一个'更重要'然后另一个?

1 个答案:

答案 0 :(得分:2)

使用INDEX关键字,您不会创建unique index,而是创建普通的非唯一索引。这就是为什么允许您插入非不同的行(field1,field2,field3)。

因此,您需要做的就是在UNIQUE构造中将索引设置为CREATE TABLE,如下例所示:

CREATE TABLE `table_a` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `field1` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
   `field2` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
   `field3` varchar(5) COLLATE latin1_swedish_ci NOT NULL DEFAULT '',
   PRIMARY KEY (`Id`),
   UNIQUE `IdxUnqiue` (`field1`(5),`field2`(5),`field3`(5))
) ENGINE=MyISAM;

插入测试数据:

REPLACE INTO table_a (Field1, Field2, Field3) VALUES ("Test1", "Test2", "Test3");
REPLACE INTO table_a (Field1, Field2, Field3) VALUES ("Test1", "Test2", "Test3");
REPLACE INTO table_a (Field1, Field2, Field3) VALUES ("Test1", "Test2", "Test3");

结果:

SELECT * FROM table_a;

+----+--------+--------+--------+
| Id | field1 | field2 | field3 |
+----+--------+--------+--------+
|  3 | Test1  | Test2  | Test3  |
+----+--------+--------+--------+
1 row in set (0.01 sec)