13

wondering how i can create a tagging system in php and with a mysql database, my initial thoughts were to create a row in the table where the articles are stored, named tags, and list the tags seperated by commas, but i am not sure how i can create a query that searches for matching tags, i dont want to have to query every article everytime someone clicks a tag. can anyone help?

Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
mcbeav
  • 11,893
  • 19
  • 54
  • 84
  • 6
    I'd suggest reading up on "database normalization". A good start would be http://en.wikipedia.org/wiki/Database_normalization. – Marc B Mar 01 '11 at 21:06

2 Answers2

40

You're describing a many-to-many relationship between Articles and Tags. You'd want to use an intermediate junction table to resolve that relationship.

enter image description here

Now, to find all articles that match a selected tag:

SELECT a.article_title
    FROM Tag t
        INNER JOIN Article_Tag_Xref atx
            ON t.tag_id = atx.tag_id
        INNER JOIN Article a
            ON atx.article_id = a.article_id
    WHERE t.tag_name = 'SelectedTagName'
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
  • 1
    What about finding all articles that match all tags of a given list? – Samuel May 08 '19 at 15:51
  • seems like there are 3 ways to do this 1) denormalized table with all tags as part of main table 2) 2 tables with the main have item id and second having item id and tag where both item id and tag are indexed and 3) the structure you described – PirateApp Oct 07 '19 at 03:41
2

tbl_articles has articleID, etc.

tbl_tags has tagID, etc.

tbl_taggedarticles has taggedArticleID, articleID, tagID

SELECT articleID FROM tbl_taggedarticles WHERE tagID = "searchedID"
Mauro
  • 589
  • 5
  • 15