简体   繁体   中英

Creating a new SQL relational database (MSSQL) from 2 other tables

Good day!

I really need your help with this, as I am in unfamiliar territory when it comes to MSSQL and building relational databases.

I typically read and write SQL data (1 table, with columns and row data), but i'd like to know how I would go about creating a relational database where I can reference both my office data with my employee data in the table tbl_accdb_assignment.

Ie. Assign an employee to a single office but also being assign multiple employees who are sharing and sitting in the same office (as displayed in my example below in excel for easy viewing)

What would be the SQL query format to ADD, DELETE, & UPDATE office data with employee data?

在此处输入图像描述

basically you'd have a table with employee information and a separate table that keeps track of locations in the building(s). You'd use foreign and primary keys to link the two tables. To ensure you don't have any employee in more than one location you'll have to write checks to kick out should an employee be found more than once on the locations table.

For such an example I'd probably have three tables, an employee table, a location table, and a table that links the two an employee-location table. Hopefully that helps.

Like this (you can extend this example)

CREATE TABLE Office(ID INT PRIMARY KEY, Name VARCHAR(100));
CREATE TABLE Employee(ID INT PRIMARY KEY, Name VARCHAR(100));
CREATE TABLE OfficeEmployee(OfficeID INT, EmployeeID INT,
  CONSTRAINT PK_OfficeEmployee PRIMARY KEY (OfficeId, EmployeeID),
  CONSTRAINT FK_OfficeEmployee_EmployeeID__Employee_ID FOREIGN KEY (EmployeeID) REFERENCES Employee(ID),
  CONSTRAINT FK_OfficeEmployee_OfficeID__Office_ID FOREIGN KEY (OfficeID) REFERENCES Office(ID)
);

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