Mysql创建有两个外键引用主键的表

标签 mysql

我有两个 mysql 表。第一个是使用以下代码创建的:

create table project(
project_id int not null auto_increment,
project_name varchar(30)
primary key(project_id));

第二个表:

create table matches(
match_id int not null auto_increment,
match_name varchar(30),
project_id int(4) foreign key (project_id) references projects(project_id));

这两个命令都可以正常工作。我想将第一个表中的project_name 列添加到第二个表中。我尝试使用

alter table projects drop primary key, add primary key(project_id, project_name);

然后

alter table matches add column project_name varchar(30), add foreign key (project_name) references projects(project_name);

但出现以下错误:

ERROR 1005 (HY000): Can't create table 'matches.#sql-55e_311' (errno: 150)

如何将第一个表中的两列都包含到第二个表中。 我的第二个表的当前结构如下:

+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| match_id   | int(11)     | NO   | PRI | NULL    | auto_increment |
| match_name | varchar(30) | YES  |     | NULL    |                |
| project_id | int(4)      | NO   | MUL | NULL    |                |
+------------+-------------+------+-----+---------+----------------+

我想将 project_name 添加为第二个表中的第四列。

最佳答案

To use a compound Primary Key as Foreign Key, you'll have to add the same number of columns (that compose the PK) with same datatypes to the child table and then use the combination of these columns in the FOREIGN KEY definition.

在此处查看相关帖子 https://stackoverflow.com/a/10566463/4904726

所以试试这个方法

alter table matches add foreign key (project_id, project_name) references projects(project_id, project_name);

关于Mysql创建有两个外键引用主键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48221279/

相关文章:

MYSQL Group 通过返回重复值

mysql - 从数据库中选择空氏族

mysql - 在mysql的表列中只查找匹配的字段值

PHP:MySQL:更新正在更新多于一行

python - 查询期间失去与 MySQL 服务器的连接

PHP MySQL从GPS获取半径用户位置的位置

mysql - 如何解密md5()中的加密密码?

mysql - 合并来自2个供应商相同产品但不同ID的两个mysql表

mySQL 从两个连接表中选择子查询中的数据总和

php - MySQL事务超时多久