Holding multiple items in a column on mysql

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I am currently creating a database, it allows a user to upload a publication, which is stored in a table called paper, it stores the paper_id, title, abstract filename and topic_id .I have a table called topic which has topic_id and topic_name which i use for the user to select a topic for their publication. However i want the user to be able to select at least 3 topics, is this possible using this system? I have run out of ideas of how to do it and help would be greatly appreciated

回答1:

Don't store topic_id in the paper table. Instead, create another normalized (many-to-many) table which links topic_id to paper_id.

/* Each paper can exist in this table as many times as necessary for all its topics */ CREATE TABLE paper_topics (   paper_id INT NOT NULL,   topic_id INT NOT NULL,   FOREIGN KEY (paper_id) REFERENCES paper (paper_id),   FOREIGN KEY (topic_id) REFERENCES topic (topic_id),   PRIMARY KEY (paper_id, topic_id) ); 

This will allow you to store as many topics per paper as necessary.

To retrieve the topics for a paper, use:

SELECT    paper.*,   topic_name FROM    paper   LEFT JOIN paper_topics ON paper.paper_id = topic.paper_id   LEFT JOIN topic ON topic.topic_id = paper_topic.topic_id WHERE paper.paper_id = <some paper id value> 

It is just about never a good idea to attempt to store multiple values in one column (such as a comma-separated list of topic_id in the paper table). The reason is that in order to query against it, you must use FIND_IN_SET() which drives up the complexity of performing joins and makes it impossible to utilize a column index when querying.



回答2:

No problem, you can use serialization, like JSON.



回答3:

Yes this is possible (using a separate table each for papers and topics). There would be a one to many relation between papers and topics.

http://www.databaseprimer.com/relationship_1tox.html



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