[英]MySql, InnoDB & Null Values
Formerly I was using MyISAM storage engine for MySql and I had defined the combination of three fields to be unique. 以前我使用MyISAM存储引擎用于MySql,我已经定义了三个字段的组合是唯一的。
Now I have switched to InnoDB, which I assume caused this problem, and now NULL != NULL. 现在我已经切换到InnoDB,我认为这导致了这个问题,现在是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. 我可以无限多次插入(Field_A,Field_B,Field_C)值(1,2,NULL)(1,2,NULL)(1,2,NULL)。
How can I prevent this behavior? 我该如何防止这种行为?
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. 取决于业务规则,但第一个想法是将
field_a
和field_b
设置为表的主键。 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: AUTO_INCREMENT列可用于非主键列,但键属性必须与auto_increment列关联:
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) : 另一种方法是添加一个唯一约束(MySQL将它们作为索引实现) :
CREATE UNIQUE INDEX blah_ind USING BTREE ON your_table(field_a, field_b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.