Reputation: 356
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
Upvotes: 2
Views: 248
Reputation: 270609
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.
Upvotes: 8
Reputation: 3198
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
Upvotes: 0