[英]Is it possible to create a Unique (Index) constraint across multiple tables?
Is there a way to create a unique index across tables in a MySQL database? 有没有办法在MySQL数据库中的表之间创建唯一索引?
By unique, I mean, 我的意思是独一无二的
table A ids=1,2,5,7...
table B ids=3,4,6,8...
I think , it is not possible by directly creating a constraint. 我认为 ,通过直接创建约束是不可能的。 But there are some solutions in order for you to get unique IDs.
但是有一些解决方案可以让您获得唯一的ID。
One suggestion would be is by using TRIGGER
. 一个建议是使用
TRIGGER
。 Create a BEFORE INSERT trigger on both tables which checks the ID for existence during INSERT
or UPDATE
. 在两个表上创建BEFORE INSERT触发器,在
INSERT
或UPDATE
期间检查ID是否存在。
Second, is by creating a third table which contains UNIQUE
numbers and the other tables: TableA
and TableB
will then be reference on the third one. 其次,通过创建包含
UNIQUE
数字和其他表的第三个表: TableA
和TableB
将在第三个表上引用。
Like JW says, this would probably work well with using a third table. 就像JW所说的那样,使用第三张表可能会很好。 In MySQL, you can use identity fields to make this easier.
在MySQL中,您可以使用标识字段来简化这一过程。 A very simple example would be using these tables (simple versions of the tables with just names without knowing any further info):
一个非常简单的例子就是使用这些表(只有名称的简单版本的表,而不知道任何进一步的信息):
CREATE TABLE a
(
`id` int,
`name` varchar(100),
PRIMARY KEY(`id`)
)
ENGINE = INNODB;
CREATE TABLE b
(
`id` int,
`name` varchar(100),
PRIMARY KEY(`id`)
)
ENGINE = INNODB;
CREATE TABLE c
(
`id` int auto_increment,
`intable` varchar(10) not null,
PRIMARY KEY(`id`)
)
ENGINE = INNODB;
Then, when you want to insert a value on either table, do (a sample inserting 'Joe' into a): 然后,当你想在任一个表上插入一个值时,do(将'Joe'插入a中的示例):
INSERT INTO c (`intable`) VALUES ('a');
INSERT INTO a (`id`, `name`)
SELECT LAST_INSERT_ID() AS id, 'Joe' AS name;
The only reason for the intable entry in c is so you know which table it was created for. 在c中输入intable的唯一原因是你知道它是为哪个表创建的。 Any sort of value to insert into c can be used instead.
可以使用任何类型的值插入到c中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.