views:

46

answers:

1

Formerly I was using MyISAM storage engine for MySql and I had defined the combination of three fields to be unique.

Now I have switched to InnoDB, which I assume caused this problem, and now NULL != NULL.

So for the following table:

ID (Auto) |  Field_A   | Field_B  | Field_C

I can insert (Field_A,Field_B,Field_C) Values(1,2,NULL) (1,2,NULL) (1,2,NULL) infinitely many times.

How can I prevent this behavior?

+1  A: 

Depends on the business rules, but the first idea would be to set field_a and field_b as the primary key for the table. An AUTO_INCREMENT column can be used for a non-primary key column, but the key attribute has to be associated with the auto_increment column:

CREATE TABLE your_table (
  ID int auto_increment not null,
  Field_A VARCHAR(45),
  Field_B VARCHAR(45),
  Field_C VARCHAR(45),
  key(ID), --without this, you'll get MySQL ERROR #1075
  primary key(field_a, field_b)
);

The other alternative is to add a unique constraint (MySQL implements them as an index):

CREATE UNIQUE INDEX blah_ind USING BTREE ON your_table(field_a, field_b)
OMG Ponies
Related: http://forums.mysql.com/read.php?22,264498,264967#msg-264967
OMG Ponies
I was able to create an index on my auto field, and then drop the primary key. I then assigned Fields A,B, and C as primary as suggested. Many thanks!
pws5068
@pws5068: Be aware that this will allow duplicates of `field_c` for every unique pair of `field_a` and `field_b` set.
OMG Ponies
You're exactly right, that is my intention in this case. Thanks again.
pws5068