Good one-to-many relation practice in MySQL

给你一囗甜甜゛ 提交于 2019-12-11 21:10:34

问题


I am developing the structure of the MySQL database and I've faced a small decisional problem about its structure.

I have 2 tables:

  1. All messages published on the site.
  2. All comments published on the site.

Every message can have more than one comment associated to it. What is a better way to make connection between a message and comments related to it?

  1. Have a field for comments that contains id of the related message.
  2. Have a field for messages that contains an array of ids of related comments in json format.

I think that usually the first method is used and then MySQL query is used to find comments that have message_id of corresponding message. But how efficient will it be when there are hundreds of thousands of comments?

Will in this case decoding json string and accessing comments by exact unique id be more efficient and fast?

I am using python for back-end if that matters.


回答1:


You should definitely add a message ID field to the comments table. Add an index on that field, and there will be no performance problems.

This solution does not break database normalization, it is logical and easy to maintain. For example, storing arrays in a single field will break normalization, which will lead to multiple problems.



来源:https://stackoverflow.com/questions/16648649/good-one-to-many-relation-practice-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!