I am trying to normalize a database I am building. One part of it is that I have many different tests that each can have many different tags. How would you deal with this?
Would you have a table with your tags and then have a limit on the number of tags per test?
I am new to databases let alone the whole idea of normalizing so forgive me if this is a very simplistic question.
Usually, this'd be dealt with using two tables. A tags
table, with each record consisting of a tag_id
and tag_name
(and potentially other metadata you want to include). Tags would then be associated with their tests via another table, test_tags
, in which test_id
and tag_id
would be stored.
If you want to limit the number of tags per test, you can easily run a SELECT COUNT(tag_id) FROM test_tags WHERE test_id=#
query to figure out how many they've already added to it.
Usually the way you would do this would be to have one table tags
, like:
INT id PRIMARY KEY
VARCHAR(255) name
Then for each object you allow to be tagged, you need a bridge table. So if you have another table tests
with its own id
column, you would have another table, tests_tags
:
INT test_id PRIMARY KEY
INT tag_id PRIMARY KEY
You can then enumerate all tests with a tag by getting the test ids where tag_id
is the tag id you are interested in; likewise you can enumerate all tags on a test by getting the tag ids where test_id
is the test id you are interested in.
This is the standard way to model a many-to-many relationship.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.