It's a classic many-to-many situation that you solve with link tables.
If tags and sub-tags are equivalent, then you have two core tables, Articles
and Tags
, and one link table ArticleTags
. If you have a pressing need to differentiate sub-tags, then you have three core tables and two link tables, Articles
, Tags
, and SubTags
linked by ArticleTags
and TagSubTags
.
The single level of tag is easier to manage and will be more performant, although whether or not it actually matters will depend on a variety of factors. If sub-tags are named very similarly then a like
search will still retrieve them, if all tags are in a single table.
To search for a articles by tag you would probably use SQL like this:
SELECT a.* FROM Articles a JOIN ArticleTags at ON a.Id = at.ArticleId JOIN
Tags t ON at.TagId = t.Id WHERE t.TagName Like '%your search criteria%'
If you are constructing SQL like this in any public environment be VERY careful to ensure you bind your parameters correctly to avoid SQL Injection Attacks link1 link2 link3
If you have distinct sub-tags then your SQL will need to be something like this
SELECT a.* FROM Articles a JOIN ArticleTags at ON a.Id = at.ArticleId
JOIN Tags t ON at.TagId = t.Id JOIN TagSubTags tst ON t.Id= tst.TagId
JOIN SubTags st ON tst.SubTagId = st.Id
WHERE t.TagName Like '%your search criteria%'
OR st.SubTagName Like '%your search criteria%'