简体   繁体   中英

Mysql: separate or common relationship tables for different entities

In my database I have different entities like todos , events , discussions , etc.
Each of them can have tags , comments , files , and other related items.

Now I have to design the relationships between these tables, and I think I have to choose from the following two possible solutions:

1. Separated relationship tables

So I will create todos_tags , events_tags , discussions_tags , todos_comments , events_comments , discussions_comments , etc. tables.

2. Common relationship tables

I will create only these tables: related_tags , related_comments , related_files , etc. having a structure like this:

related_tags

  • entity (event|discussion|todo|etc. - as enum or tinyint (1|2|3|etc.))
  • entity_id
  • tag_id

Which design should I use?

Probably you will say: it depends on the situation, and I think this is correct.

I my case most of the time (maybe 70%+) I will have to query only one of the entities (events, discussion or todos), but in some cases I need them all in the same query (both events, discussion, todos having a specified tag for example). In this case I'll have to do on union on 3+ tables (in my case it can be 5+ tables) if I go with separated relationship tables .

I'll not have more than 1000-2000 rows in each table(events, discussions, todos);

What is the correct way to go? What are some personal experiences about this?

The second schema is more extensible. This way you will be able to extend your application to construct queries involving more than one type. In addition, it's possible to easily add new types to the future even dynamically. Furthermore, it allows greater aggregation freedom, for example allowing you to count how many rows in each type exist, or how many were created during a particular timeframe.

On the other hand, the first design does not really have many advantages other than speed: But MySQL is already good at handling these types of queries fast enough for you. You can create an index "entity" to make it work smoothly. If in the future you need to partition your tables to increase speed, you can do so at a later stage.

It is a far simpler design to have a single, common relationship table such as related_tags where you specify the entity type in a column rather than having multiple tables. Just be sure you properly index the entity and tag_id fields together to have optimum performance.

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