在MySQL中存储多对多关系的最佳方式? [英] Best way to store a many-to-many relationship in MySQL?

查看:256
本文介绍了在MySQL中存储多对多关系的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含表'posts'和'tags'的简单数据库。帖子可以有许多标签和标签可以属于许多帖子。

Let's say I have a simple database with tables 'posts' and 'tags'. Posts can have many tags and tags can belong to many posts.

什么是最好的结构数据库的方法?我想到使用list / serialize:

What is the best way to structure the database? I thought of using a list/serialize:

tags
idx tag_id, str tag_name

posts
idx post_id, str title, list tag_ids

。问题是使用这个我甚至不知道如何结构化查询以拉我关联标签名称当我得到一个职位。

OR having another table with the associations. Problem is using this I don't even know how to structure the query to pull the associated tag names when I get a post.

posts
idx post_id, str title

post_tags
fk post_id, fk tag_id

我实际上我不喜欢他们。是否有更好的方法?

I actually I don't like either of them. Is there a better way?

推荐答案

post_tags 在数据库中实现多对多关系。

The post_tags is the proper means of implementing a many to many relationship in the database.

我对您发布的内容唯一的补充是,它的两个列都应该是主键,以确保没有重复。

The only addition I'd make to what you posted is that both columns in it should be the primary key to ensure there are no duplicates.

这篇关于在MySQL中存储多对多关系的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆