简体   繁体   中英

Multi tenancy design - sharing data between schemas

Let's consider such case:

  1. User can have a company (or many of them)
  2. User can be a part of a company (or in many of them)
  3. Company is a single tenant of the system
  4. Company has a list of tasks
  5. Each task is assigned to a user

Now given the circumnstaces above, I want to implement a system in which each company (tenant) has a separate schema for its tasks, but the problem is that for each task I also need a user data from the main schema.

The question is how to approach this problem

The possible solutions I have thought of (but none is really convincing me):

  1. Copying all users data matched with a company to company's schema (it would require a fair amount of synchronization, therefore I don't find it very efficient)
  2. Switching between schemas and 'merging' them programmatically - this one involves a lot of additional code to implement and it violates good practices - as the user_id in task would reach outside the tanant's schema)

I hope there is a better solution I haven't thought of. Please note that this is a simplified case, just to describe the problem.

It sounds like you want a handful of tables, like users , companies , tasks , and related tables.

In general, you do not want to split entities across multiple tables. Here are some reasons.

  1. It is easier to maintain a handful of tables rather than hundreds or thousands of tables.
  2. Databases are more efficient on larger tables. A proliferation of small tables results in lots of partially filled data pages for a single entity.
  3. Certain queries -- such as how many tasks are in each company -- are much easier with a single table.
  4. With multiple tables, such queries often require resorting to dynamic SQL, which is just a mess for simple tasks.
  5. Restructuring the data becomes a nightmare when you have to apply the restructuring to a zillion tables rather than a handful of tables.
  6. Adding new features is a nightmare when it has to be repeated multiple times.

There are some rare circumstances where it makes sense to separate data. For instance, if the application is going to be on-premise at each company, then you have no choice. Similarly, you might have legal requirements for keeping data physically separate. But from a strict database-design perspective, you want one table per entity.

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