无法为设置了两个主键的 table 创建外键

Cant create a foreign key for a table that has two primary keys set

我正在尝试创建一个从一个 table 指向另一个的外键。这些是 tbl_inventorytbl_player。玩家 table 设置了两个主键,player_scoreplayerID。当我尝试在清单 table 中创建外键以获取玩家 ID 时。它抛出以下错误:

这是我的 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)
);

我做了一些故障排除,发现当我只定义一个主键时它可以工作,但我正在处理的项目需要两个。有人知道如何解决这个错误吗?

你有一个复合主键,所以你需要一个复合外键:

/*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)
);

您也可以尝试将一个主键和另一列作为唯一键:(仅当它适用于您的项目时,将 table 的单列作为主键,其他列作为唯一键)

/*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)
);

干杯!!