[英]Do I need to put multiple Id's in a table if I want to get 3 different Id's(with other info) from another table?
I am learning about SQL and tables, foreign keys, etc. To try it instead of only learning it I created 2 tables:我正在学习 SQL 和表、外键等。为了尝试而不是只学习它,我创建了 2 个表:
Table 1: Team
:表 1: Team
:
Table 2: Karakter
(that is "character" in Dutch)表 2: Karakter
(即荷兰语中的“字符”)
A team has an Id ( TeamId
), UserId ( GebruikerId
, this is not important for now), name ( Teamnaam
) and CharacterId ( KarakterId
).一个团队有一个 Id ( TeamId
)、UserId ( GebruikerId
,目前这并不重要)、 name ( Teamnaam
) 和 CharacterId ( KarakterId
)。
I want a team to exist of 3 characters ( karakters
), and I know I can find character via foreign keys, but sins I want 3 characters and not only 1 I was wondering if in my table TeamI need to put KarakterId1, KarakterId2, KarakterId3?我想要一个由 3 个字符( karakters
)组成的团队,我知道我可以通过外键找到字符,但是我想要 3 个字符而不仅仅是 1 个我想知道是否在我的表中 TeamI 需要放置 KarakterId1、KarakterId2、KarakterId3 ?
Or do you usually do this in another simpler way that I don't know of (Because I can not find it)还是您通常以我不知道的另一种更简单的方式执行此操作(因为我找不到它)
Thanks in advance!提前致谢!
That's a many-to-many relationship between teams and characters: where one team has several characters, and a given character may belong to more than one team.这是团队和角色之间的多对多关系:一个团队有多个角色,而一个给定的角色可能属于多个团队。
A normalized design implies creating a third table, called a bridge table, to represent that relationship, with one row for each team/character tuple, and foreign key constraints the reference the parent tables.规范化设计意味着创建第三个表,称为桥表,以表示该关系,每个团队/角色元组占一行,外键约束引用父表。
create table teams (
team_id int primary key,
user_id int not null,
name varchar(50)
);
create table characters (
character_id int primary key,
name varchar(50)
);
create table team_characters (
team_id int references teams(team_id),
character_id int references characters(character_id),
primary key (team_id, character_id)
);
Precisely verbalizing the constraint in natural language usually reveals the correct solution.用自然语言精确地表达约束通常会揭示正确的解决方案。 Here are two possible examples, there can be more.这里有两个可能的例子,可能还有更多。
karakter {K}
PK {K}
team {T}
PK {T}
team_karakter {T, K}
PK {T, K}
FK1 {K} REFERENCES karakter {K}
FK2 {T} REFERENCES team {T}
karakter {K}
PK {K}
team {T, K1, K2, K3}
PK {T}
FK1 {K1} REFERENCES karakter {K}
FK2 {K2} REFERENCES karakter {K}
FK3 {K3} REFERENCES karakter {K}
CHECK ((K1 <> K2) AND (K1 <> K3) AND (K2 <> K3))
Note:笔记:
All attributes (columns) NOT NULL
PK = Primary Key
FK = Foreign Key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.