小编典典

MySQL Relationships

mysql

I am trying to figure out how to structure this database. I have used Apple’s
core data before just fine, I’m just working on a different project now that
requires MySQL. I am very new to MySQL so please go easy on me. :)

For this example, let’s say I have three tables, User, Device, and
Location. Drawing it out, a Location can have many Devices, but the
Device can only have one Location; Each User has its primary key,
UserID, of which I need to use to fetch the correct information.

So how do I create a relationship like this here? I’ve heard of creating an
index and a foreign key and I’m not sure how they work exactly.

In the end, what I need to do is be able to access the User‘s specific table
and view all of the Locations associated with that User. I will also need
to be able to add a Device at a certain Location for a certain User.

Again, please forgive me as I’m trying to wrap my head around MySQL. I am
using HeidiSQL to do my database editing.


阅读 503

收藏
2020-05-17

共1个答案

小编典典

User - Device is a many-to-many relationship, so you’ll want to introduce an
intermediary table to resolve that relationship. That table simply consists of
two foreign keys, one referencing the User table and one referencing Device.
Device - Location can be handled with a simple foreign key in the Device table
pointing to a Location table.

enter image description here

2020-05-17