我有一个表,其中有两列用于存储另一个表中的 id。 Column1 从 ABC 表获取 id,Column2 也从该表获取 id,但字母称为父 ID,因此通过这些信息我知道谁是谁的父代。
现在我想创建一个约束,永远不要让两列获得相同的 id。 以下无效:
ALTER TABLE id_parent_table
ADD CHECK (parent_id != main_id)
这仍然允许插入两个相同的数字。
最佳答案
从 MySQL 8.0.16 开始支持此功能。
参见https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
mysql> create table id_parent_table (
-> main_id bigint unsigned not null,
-> parent_id bigint unsigned not null,
-> constraint columns_cannot_equal check (main_id <> parent_id)
-> );
Query OK, 0 rows affected (0.38 sec)
mysql> insert into id_parent_table (main_id, parent_id) values (1, 1);
ERROR 3819 (HY000): Check constraint 'columns_cannot_equal' is violated.
关于mysql - SQL 约束使 2 列彼此不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23130642/