views:

25

answers:

1

I have a MySQL (5.0) table with 3 rows which are considered a combined Unique Index:

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;

This table should be filled with a REPLACE INTO query:

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

The behavior I'd like to see is that this query always overrides the previous inserted row, because IdxUnique is...ahm, triggered. But unfortunately, there's still the primary index which seems to kick in and always inserts a new row.

What I get:

Query was executed 3 times:

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

What I want:

Query was executed 3 times:

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

So, can I tell REPLACE INTO to use just a certain Index or to consider one 'more inportant' then another?

+1  A: 

With the INDEX keyword you are not creating a unique index, but a normal non-unique index. That is why you are being allowed to insert rows with non-distinct (field1, field2, field3).

Therefore all you need to do is to set your index as UNIQUE in your CREATE TABLE construct, as in the following example:

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;

Insert the test data:

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");

Result:

SELECT * FROM table_a;

+----+--------+--------+--------+
| Id | field1 | field2 | field3 |
+----+--------+--------+--------+
|  3 | Test1  | Test2  | Test3  |
+----+--------+--------+--------+
1 row in set (0.01 sec)
Daniel Vassallo
Whoops...my mistake, I just forget to check the box. Ahm, but that's working...odd...that means I've a logical error somewhere in my 'real' table, screwing with my index. Thanks anyway!
Bobby