简体   繁体   English

MySQL-来自一个表的许多外键

[英]MySQL - many foreign keys from one table

im making database for game... the problem is I don't know much about databases. 我正在为游戏制作数据库...问题是我对数据库了解不多。 Here are my tables i have problem with: 这是我遇到的问题:

CREATE TABLE items(
name VARCHAR(30) PRIMARY KEY,
type VARCHAR(20) NOT NULL,
atk INT,
def INT,
arm INT,
price_buy SMALLINT UNSIGNED,
price_sell SMALLINT UNSIGNED);

CREATE TABLE equipment (
id_eq INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
head_s VARCHAR(30),
body_s VARCHAR(30),
right_s VARCHAR(30),
left_s VARCHAR(30),
feet_s VARCHAR(30),
slot1 VARCHAR(30),
slot2 VARCHAR(30),
slot3 VARCHAR(30),
slot4 VARCHAR(30),
slot5 VARCHAR(30),
slot6 VARCHAR(30),
slot7 VARCHAR(30),
slot8 VARCHAR(30),
slot9 VARCHAR(30),
slot10 VARCHAR(30).
FOREIGN KEY (head_s) REFERENCES items(name),
FOREIGN KEY (body_s) REFERENCES items(name),
FOREIGN KEY (right_s) REFERENCES items(name),
FOREIGN KEY (left_s) REFERENCES items(name),
FOREIGN KEY (feet_s) REFERENCES items(name),
FOREIGN KEY (slot1) REFERENCES items(name),
FOREIGN KEY (slot2) REFERENCES items(name),
FOREIGN KEY (slot3) REFERENCES items(name),
FOREIGN KEY (slot4) REFERENCES items(name),
FOREIGN KEY (slot5) REFERENCES items(name),
FOREIGN KEY (slot6) REFERENCES items(name),
FOREIGN KEY (slot7) REFERENCES items(name),
FOREIGN KEY (slot8) REFERENCES items(name),
FOREIGN KEY (slot9) REFERENCES items(name),
FOREIGN KEY (slot10) REFERENCES items(name));

I have doubts about this solution, could anyone tell me is this the right way? 我对此解决方案有疑问,有人可以告诉我这是正确的方法吗?

In general, this is not the right way, unless you have exactly 7 slots that are labelled 1 though 7 and you are putting items into some or all of them. 通常,这不是正确的方法,除非您恰好有7个标记为1到7的插槽,并且要将项目放入其中的一些或全部中。

The more typical way is a junction table: 更典型的方法是联结表:

create table EquipmentItems (
    EquipmentItemId int primary key auto_increment,
    EquipmentId int,
    ItemId int,
    constraint fk_equipmentitems_equipment foreign key (EquipementId) references Equipement(id_eq),
    constraint fk_equipmentitems_item foreign key (ItemId) references items(ItemId)
);

If you look at this carefully, you'll note that I added a synthetic key to Items . 如果仔细看一下,您会注意到我在Items添加了一个合成键。 This is a good idea for foreign key references, because integers are generally more compact than strings. 对于外键引用,这是一个好主意,因为整数通常比字符串更紧凑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM