简体   繁体   中英

Database Design: Multiple join tables or one table with identifying 'table' column

I'm designing a database where any content can be tagged and I'm likely to want to be able to select all content with a specific tag.

I'm struggling with the following two options and would appreciate some advice. If there's a better way please let me know.

Option A
Multiple 'many to many' join tables.

tag:
  id
  tag

media:
  id
  title
  src
  creation

media_tags:
  id
  media_id
  tag_id

article:
  id
  title
  content
  creation

article_tags:
  id
  article_id
  tag_id

Options B
A single 'tag reference' table, which uses a 'table' column to identify which table to join to.

tag:
  id
  tag

tag_reference:
  id
  row_id
  tag_id
  table

media:
  id
  title
  src
  creation

article:
  id
  title
  content
  creation

From a maintenance point of view option B seems favorable but considering the SQL query to select all content and don't think it's possible without multiple queries.

When using Option B , you can't set up foreign keys to the other tables. Thus I would go with Option A and one table for each m:n relation.

"From a maintenance point of view option B" – is a nightmare. What happens if you delete an article? All the rows with that row_id will persist in tag_reference table. You always need to update those entries manually.

Option B contains a multivalued dependency - and as such is breach of 4th normal form . I much prefer Option A

Actually, It depends on every sql developer. But I prefer Option A since you can easily know that a certain column in a table is a foreign key ( assuming it's true ) of the other table.

Option B is somewhat bad design because storing table names in a column is bad idea. You can spend more IF or CASE here.

The second option pretty much prevents you using any JOINs for efficient SQL, forcing you into using slow multiple selects.

So I would say the first option is far preferable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM