Possible Duplicate:
Is storing a comma separated list in a database column really that bad?
This is a problem I often encounter when trying to expand the database.
For example:
I want to keep track of how many users saw a particular article in my website, so in the database I added a views field to the article table. Now, if I wanted to make sure that these are unique views then this is clearly not enough.
So let’s say that in my design I can identify a user (or at least a computer) with a single number that’s stored along with an IP or something.
Then, if I wanted to keep track of how many unique users saw a particular article which is the best way to go?
- To create another table
article_viewswith the fieldsarticle_idand
user_id. - To save the
user_ids separated by commas inside theviewsfield of thearticletable.
Never, ever, ever choose the separate-by-commas solution. It is a violation of every principle of database design. Create a separate table instead.
In your particular case, create the table with the PRIMARY KEY on (article_id, user_id). The database will then prohibit the entry of duplicate records. Depending on your SQL engine, you can additionally use INSERT OR IGNORE (or equivalent) to avoid throwing exceptions.
The other solution requires you to enforce the uniqueness in the all applications that touch the data.