一对多 MySQL
可能的重复:
MySQL 关系
我正在尝试使用外键在 MySQL 中创建一对多关系。
两个表,user
和 location
。每个用户
可以有多个位置
,但每个位置
只能有一个用户
。
我该如何配置这个?如果有帮助的话,我正在使用 HeidiSQL,尽管我也可以输入代码。
Possible Duplicate:
MySQL Relationships
I am trying to create a one to many relationship in MySQL with foreign keys.
Two tables, user
and location
. Each user
can have many location
s, but each location
can have only one user
.
How do I configure this? I am using HeidiSQL if that helps, though I can input code as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MySQL 不知道,也不需要知道关系是 1-1 还是 1-many。
没有 SQL 支持多对多关系,所有 SQL 都需要一个中间表,将多对多关系拆分为 2 个独立的 1-多关系。
区别在于控制关系的逻辑,即您编写的代码中的逻辑。
通过让表共享相同的主键 (PK) 来维护 1-1 关系。
辅助表声明 PK 作为指向其他表 PK 的外键。
关系的方向
1 -> Many
与many <- 1
由链接字段的位置决定。通常每个表都有一个唯一的
id
,链接字段称为tablename_id
。包含链接字段的表是关系的
many
端,另一个表位于1
端。通过将链接字段放置在
location
表中,您可以强制执行某个位置只能有 1 个用户的操作。然而,一个用户可以有多个位置。MySQL does not know, nor does it need to know if a relationship is 1-1, or 1-many.
No SQL supports many-many relationships, all require a intermediate table which splits a many-many relationship into 2 separate 1-many.
The difference is in the logic that controls the relationships, which is in the code that you write.
A 1-1 relationship is maintained by having the tables share the same primary key (PK).
With the secondary table declaring that PK as a foreign key pointing to the other tables PK.
The direction of the relationship
1 -> many
vsmany <- 1
is determined by the location of the link field.Usually every table has a unique
id
and the link field is calledtablename_id
.The table that has the link field in it is the
many
side of the relationship, the other table is on the1
side.By placing the link field in the
location
table, you force things so that a location can only have 1 user. However a user can have many locations.这里有一个例子几乎正是您所需要的 innodb 中的外键
在您的示例中,用户与父级相同(一个用户有多个位置,一个父级有多个子级),并且位置与子级相同(一个位置有一个用户,一个子级有一个父级) )
There is an example here that is almost exactly what you need foreign keys in innodb
In your example user is the same as parent (a user has many locations, a parent has many childs) and location is the same as child (a location has one user, a child has one parent)