Question

I know how to make a simple messaging schema for one to one user messaging ( all user come from same table) but my problem is that I have multiple Table with different type of users which have their primary keys now when a user from one table want to send a message to a user from another table then what should be schema for this application, Let I have these three tables with different type of users-

TableA- id | Name |...
TableB- id | Name | ...
TableC- id | Name | ...

Now a user from TableA want to send a message to a user from TableB or TableC then what should be database schema for messaging app (all three tables can have different user with same primary key i.e id)

Was it helpful?

Solution

Storing the same types of data with slightly differing properties is antithetical to databases. You can make it work by pointing to Table.ID within your application, but it's not pretty and not best practice.

What you're looking for is a single users table with one or more flags or references (more columns/fields in the table) indicating what details are different for each user. If you need multiple user groups, you should simply have groups table.

eg.:

# users table
CREATE TABLE users (
  user_id INT,
  user_name VARCHAR(32),
  group_id INT,
  talk_outside_group BOOL
);

# groups table
CREATE TABLE user_groups (
  group_id INT,
  group_name VARCHAR(32),
);

INSERT INTO user_groups SET group_id = 1, group_name = 'PHBs';
INSERT INTO user_groups SET group_id = 2, group_name = 'HR';

INSERT INTO users SET user_id = 1, group_id = 1, user_name = 'Alice';
INSERT INTO users SET user_id = 2, group_id = 1, user_name = 'Bob';
INSERT INTO users SET user_id = 3, group_id = 2, user_name = 'Carol';
INSERT INTO users SET user_id = 4, group_id = 2, user_name = 'Dave';

In this example, Alice and Bob are PHBs and can barely work their keyboards.

Carol and Dave are HR drones and have boring conversations ;)

When and whether users of separate groups can talk to each other could be indicated by a flag in either table (depending on how granular you need the privilege control... in this example, the talk_outside_group field) and should be handled in the application layer.

OTHER TIPS

Your users shouldn't be in different tables.

If you want some users to have privileges then do a table "privileges" and link it to "users" with a table "user_privilege" which would contain "id_user" and "id_privilege".

If you really want to do what you are doing, then you'll have to add a field "table_name" in the message table to be able to know from where the user is coming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top