Mysql数据库...主键和外键[重复]

时间:2022-04-16 00:13:57

This question already has an answer here:

这个问题在这里已有答案:

I'm kinda new at mysql database so I'm sorry if this is kinda noob question... if I have 2 database, database a and database b.. then I created 1 table in each database.. can I use the table in database b to connect to the table in database a to have a foreign and primary key? or it can only be connected between tables on the same database?

我是mysql数据库的新手,所以我很抱歉,如果这是一个noob问题...如果我有2个数据库,数据库a和数据库b ..然后我在每个数据库中创建了1个表..我可以使用表在数据库b中连接到数据库a中的表有一个外键和主键?或者它只能连接在同一个数据库的表之间?

1 个解决方案

#1


0  

I think your question is "can foreign key columns reference columns in another database." The answer is "yes they can."

我认为你的问题是“外键列可以引用另一个数据库中的列。”答案是“是的,他们可以。”

CREATE DATABASE a; USE a;
CREATE TABLE a1 (id int not null auto_increment primary key);
CREATE DATABASE b; USE b;
CREATE TABLE b1 (id int, aid int, foreign key (aid) references a.a1 (id));

#1


0  

I think your question is "can foreign key columns reference columns in another database." The answer is "yes they can."

我认为你的问题是“外键列可以引用另一个数据库中的列。”答案是“是的,他们可以。”

CREATE DATABASE a; USE a;
CREATE TABLE a1 (id int not null auto_increment primary key);
CREATE DATABASE b; USE b;
CREATE TABLE b1 (id int, aid int, foreign key (aid) references a.a1 (id));