简体   繁体   中英

How to create a relation with multiple tables in mysql?

What I'm doing now, possibly mistaken:

users:
id,name

actions:
id, user_id

events:
id, action_id, description

posts
id, event_id, text

What I would like:

A User can create many actions.

An Action can have one Event

An Event can have many posts, but should be related to just one Event

The "trick" is I want that my Actions to have many posts, so I assume that creating the Event table was right.

What kind of relation should be set up assuming this?

Since An Action can have many posts but should be related to just one Event , this is a simple join.

SELECT users.*, actions.*, events.*, posts.* FROM users 
LEFT JOIN actions ON users.id = actions.user_id 
LEFT JOIN events ON actions.id = events.action_id
LEFT JOIN posts ON events.id = posts.events_id

As mentioned in the comment above, there is not a need for the events table if an action is only ever going to have only 1 event AND the event is unique to that action - meaning the event won't be used in the future by another action.


Regarding you comment above that An Action can have many posts but should be related to many Events , this wouldn't change the join.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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