简体   繁体   English

如何在mysql中创建具有多个表的关系?

[英]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. “窍门”是我希望我的操作包含很多帖子,因此我认为创建Event表是正确的。

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. 由于An Action can have many posts but should be related to just one Event ,所以这是一个简单的联接。

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. 关于您在上面的评论, An Action can have many posts but should be related to many Events ,但这不会改变联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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