Search code examples
mysqlnormalizationrdbmsdatabase-normalization

4 tables in my DB need a field called, "categories". How can I make this work?


For my RSS aggregator, there a four tables that represent rss and atom feeds and, their articles. Each feed type and entry type will have zero or more categories. In the interest of not duplicating data, I'd like to have only one table for categories.

How can I accomplish this?

enter image description here


Solution

  • One way is to keep categories in one single table - e.g. category - and define an X table for each entity/table that needs 0 or more category associations:

    rssFeedXCategory

    rssFeedId INT FK -> rssFeed (id)
    categoryId INT FK -> category (id)
    

    atomFeedXCategory

    atomFeedId INT FK -> atomFeed (id)
    categoryId INT FK -> category (id)    
    

    and so on.

    You can define a PK for both columns in each table, but an extra identity column may also be used. When working with an ORM, I also have an extra identity/autoincrement column (e.g. XId INT), so that a single column can be used to identity a row.