[英]Cant create a foreign key for a table that has two primary keys set
I am trying to create a foreign key pointed from one table to another.我正在尝试创建一个从一个表指向另一个表的外键。 these being
tbl_inventory
and tbl_player
.这些是
tbl_inventory
和tbl_player
。 The player table has two primary keys set, player_score
and playerID
. player 表有两个主键集,
player_score
和playerID
。 When I try to create a foreign key within the inventory table to get the playerID.当我尝试在库存表中创建外键以获取 playerID 时。 it throws the error below:
它抛出以下错误:
Here is my SQL script:这是我的 SQL 脚本:
drop database if exists example_db;
create database example_db;
use example_db;
/*Player ===================================================================================*/
drop table if exists tbl_player;
CREATE TABLE `tbl_player` (
`player_score` INTEGER DEFAULT 0 NOT NULL,
`playerID` INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT SYS_PK_10375 PRIMARY KEY (`player_score`,`playerID`)
);
/*Inventory ===================================================================================*/
drop table if exists tbl_inventory;
CREATE TABLE `tbl_inventory` (
`inventoryID` INTEGER NOT NULL,
`playerID` INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT SYS_PK_10520 PRIMARY KEY (`inventoryID`),
FOREIGN KEY (playerID) REFERENCES tbl_player(playerID)
);
I did some troubleshooting and found that it works when I only define one primary key, but two are required for the project that I am working on.我做了一些故障排除,发现当我只定义一个主键时它可以工作,但我正在处理的项目需要两个。 Does anybody know how to fix this error?
有谁知道如何解决这个错误?
You have a composite primary key, so you need a composite foreign key:你有一个复合主键,所以你需要一个复合外键:
/*Inventory ===================================================================================*/
drop table if exists tbl_inventory;
CREATE TABLE `tbl_inventory` (
`inventoryID` INTEGER NOT NULL,
`playerID` INTEGER DEFAULT 0 NOT NULL,
`player_score` INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT SYS_PK_10520 PRIMARY KEY (`inventoryID`),
FOREIGN KEY (player_score,playerID) REFERENCES tbl_player(player_score,playerID)
);
Also you can may be try having one primary key and the other column as unique: (only if it works for your project to have single column of table as primary and other as unique)您也可以尝试将一个主键和另一列设为唯一:(仅当它适用于您的项目将表的单列作为主键而其他列作为唯一时)
/*Player ===================================================================================*/
drop table if exists tbl_player;
CREATE TABLE `tbl_player` (
`player_score` INTEGER DEFAULT 0 NOT NULL,
`playerID` INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT SYS_PK_10375 PRIMARY KEY (`playerID`),
UNIQUE(`player_score`)
);
/*Inventory ===================================================================================*/
drop table if exists tbl_inventory;
CREATE TABLE `tbl_inventory` (
`inventoryID` INTEGER NOT NULL,
`playerID` INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT SYS_PK_10520 PRIMARY KEY (`inventoryID`),
FOREIGN KEY (playerID) REFERENCES tbl_player(playerID)
);
Cheers!!干杯!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.