我有下表,我正在尝试在该表上创建一个约束,该约束指出 Ter_ID 列
可以具有相同的 Ter_ID
重复,但相应的 状态
在任何时候都不可能相同,因此,例如,如果有人尝试将Ter_ID 100P Status
从U
更新为A
它不会看到已经有一行包含相应的数据。
Ter_ID Status Address
100P A Road1
100P U Road2
200R A Road2
最佳答案
您需要使用两列添加组合唯一索引。
示例:
ALTER TABLE `tablename` ADD UNIQUE `unique_index`(`Ter_ID`, `Status`);
请注意不同的 NULL 行为,具体取决于您使用的 MySQL 引擎。来自MySQL官方文档:
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.
关于mysql - 在mysql表上创建重复约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26040930/