一对多 MySQL

One to Many MySQL(一对多 MySQL)
本文介绍了一对多 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
MySQL 关系

我正在尝试使用外键在 MySQL 中创建一对多关系.

I am trying to create a one to many relationship in MySQL with foreign keys.

两个表,userlocation.每个user可以有多个location,但每个location只能有一个user.

Two tables, user and location. Each user can have many locations, but each location can have only one user.

我该如何配置?如果有帮助,我正在使用 HeidiSQL,不过我也可以输入代码.

How do I configure this? I am using HeidiSQL if that helps, though I can input code as well.

推荐答案

MySQL 不知道,也不需要知道关系是 1-1 还是 1-many.
没有 SQL 支持多对多关系,都需要一个中间表,将多对多关系拆分为 2 个单独的 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.

区别在于控制关系的逻辑,这在您编写的代码中.
通过让表共享相同的主键 (PK) 来维护 1-1 关系.
辅助表将 PK 声明为指向其他表 PK 的外键.

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.

Table chinese_mother (
id integer primary key,
name....
   

Table chinese_child (
id integer primary key,
name ....
....,
foreign key (id) references chinese_mother.id

关系的方向1 ->many vs many <- 1 由链接字段的位置决定.

The direction of the relationship 1 -> many vs many <- 1 is determined by the location of the link field.

通常每个表都有一个唯一的id,链接字段称为tablename_id.
包含链接字段的表是关系的many 侧,另一个表在1 侧.

Usually every table has a unique id and the link field is called tablename_id.
The table that has the link field in it is the many side of the relationship, the other table is on the 1 side.

每个用户可以有多个位置,但每个位置只能有一个用户.

Each user can have many locations, but each location can have only one user.

Table user
id: primary key
name......
.....

Table location
id: primary key
user_id foreign key references (user.id)
x
y
.......

通过将链接字段放在 location 表中,您可以强制要求一个位置只能有 1 个用户.但是,一个用户可以拥有多个位置.

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.

这篇关于一对多 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)