Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many tables for many users?

I have a web application that in many ways can be considered to be a multi-tenant environment. By this I mean that each user of the application gets their own 'custom' environment, with absolutely no interaction between those users.

So far I have built the web application as a 'single user' environment. In other words, I haven't actually done anything to support multi-users, but only worked on the functionality I want from the app. Here is my problem... What's the best way to build a multi-user environment:

  1. All users point to the same 'core' backend. In other words, I build the logic to separate users via appropriate SQL queries (eg. select * from table where user='123' and attribute='456').
  2. Each user points to a unique tablespace, which is built separately as they join the system. In this case I would simply generate ALL the relevant SQL tables per user, with some sort of suffix for the user. (eg. now a query would look like 'select * from table_ where attribute ='456').

In short, it's a difference between "select * from table where USER=" and "select * from table_USER".

like image 891
Shaun_web Avatar asked May 17 '10 23:05

Shaun_web


People also ask

How many tables does a many-to-many relationship?

Connect the three tables to create the many-to-many relationship. To complete the many-to-many relationship, create a one-to-many relationship between the primary key field in each table and the matching field in the intermediate table. For details on how to do this, see Get started with table relationships.

How do you deal with many-to-many relationships?

Many-to-many (m:n) relationships add complexity and confusion to your model and to the application development process. The key to resolve m:n relationships is to separate the two entities and create two one-to-many (1:n) relationships between them with a third intersect entity.

Should many-to-many table have ID?

You would never need to join or filter on such an ID. You would only join or filter on the ID's of the tables you're mapping. An ID on a junction table is a waste of disk space. So the "best" option is to avoid the ID.


2 Answers

Creating tables dynamically is rather dirty and confusing. Additionally, if you have lots of users it'll be a complete chaos if you have tons of tables - especially if you need to change something in n tables instead of a single table.

--> Use one table and add some user_id column. With proper indexes this will be as fast or even faster than separate tables.

like image 148
ThiefMaster Avatar answered Sep 20 '22 06:09

ThiefMaster


the first option is better.

In general tables should contain normalized data, you shouldn't duplicate the same table.

Also the 1st option is safer, as you don't need to grant the ability to create or drop real tables to the program

like image 23
Brian Avatar answered Sep 18 '22 06:09

Brian