mysql - 在mysql表上创建重复约束

标签 mysql constraints

我有下表,我正在尝试在该表上创建一个约束,该约束指出 Ter_ID 列 可以具有相同的 Ter_ID 重复,但相应的 状态在任何时候都不可能相同,因此,例如,如果有人尝试将Ter_ID 100P StatusU更新为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/

相关文章:

mysql - Codeigniter 用不同的值更新表列

mysql - 使用mysql中的存储过程执行sql

mysql - Access 中的数据单元 "#Deleted"- ODBC、MySQL 和 BIGINT 唯一 ID

sql - 在 SQL Server 上使用与不使用 CONSTRAINT 关键字的区别

ios - 如何向放置在 UIStackView 中以编程方式创建的 UIButton 添加约束

Swift 约束使错误元素宽度变小

mysql偶尔会重启

php - 如何在带有 'IN' 运算符的 Mysql 查询中使用数组值?

ios - 如何在 Storyboard 中使 UiView 尊重百分比

python - 在 scipy.optimize.fmin_cobyla 中为参数估计指定约束时出错