简体   繁体   中英

Model Sql relation many to many of the same entity

In my app I have business objects:

Business Id Name Type: Business or Independent Professional Persons

Persons will be a list of Independent professionals that are working for that business.

What do you propose as tables. My first thought was to have Business table with a Type column. Then to have another table:

BusinessProfesionals BusinessId BusinessProfessionalId

both keys will refer business table Id column.

I am thinking at this because usually on website I consider Independent Professional the same as Business. But I also need to show sometimes which Independent Professional works for a certain business.

Does this make sense?

It is a common problem in data modeling two conflate to concepts. In this case just because a person is the business it does not make them the same entity.

Consider John Frank Enterprises LLC. The only employee is John Frank. The question when modeling should not be: "Is the fact that this is a single-person business described explicitly in the model?" The question should be: "Can I construct a performant query that will identify businesses by the number of employees.

So if you have the following tables in pseudo-SQL. Note the convention for physical primary keys defining the relationships:

business_type (
  business_type_id int primary_key,
  business_type_name varchar(50),
)

business (
  business_id int primary_key,
  business_type_id int foreign_key # Now the business is described,
  business_name varchar(255),
)

independent_professional (
  independent_professional_id int primary_key,
  first_name varchar(50),
  last_name varchar(50),
)

business_independent_professional (
  business_independent_professional int primary_key, 
  business_id int foreign_key,
  independent_professional_id int foreign_key,
)

This model is now general enough to let any professional work at zero or more business while any business can hire zero or more of these professionals.

It will tell you with a query which businesses have only one employee or which business names match a professionals name.

In the business logic of the application you can also do something like look for the business_type of DBA (doing-business-as, not database admin) and ensure upon insert, update or delete that they are a business of only one person and their business_name matches their professional_name. (This is actually too restrictive but seeks to illustrate the difference between modeling relationships between entities vs. business logic)

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