简体   繁体   中英

Intersection of Two Tables in SQL

Basically I need to create a new table that uses specific information from two other tables.

For example, I have a table called person with the elements person_id, first_name, last_name, gender, age, and fav_quote. I have a second table called department with the elements dept_id, dept_name, and building. I now need to create and intersection table with the person_id and dept_id elements included. And both must be the primary key (which I assume just means PRIMARY KEY (person_id, dept_id) command in my source).

CREATE TABLE person (

person_id INT(8) NOT NULL auto_increment,

first_name VARCHAR(25) NOT NULL,

last_name VARCHAR(25) NOT NULL,

gender VARCHAR(1),

age INT(8),

fav_quote TEXT,

PRIMARY KEY (person_id)

);

CREATE TABLE department (

dept_id INT(8) NOT NULL auto_increment,

dept_name VARCHAR(25) NOT NULL,

building VARCHAR(25) NOT NULL,

PRIMARY KEY (dept_id)

);

That is the code I have for the initial two tables I'm just not sure how to create an intersection and, having gone back over my notes, I can't find the instructions on how to write it.

You got the primary key part right. I'd add foreign keys to your existing table in order to prevent creating interactions with people or departments that don't exist:

CREATE TABLE person_department
    person_id INT(8) NOT NULL,
    dept_id INT(8) NOT NULL,
    PRIMARY KEY(person_id, dept_id),
    FOREIGN KEY(person_id) REFERENCES person(person_id),
    FOREIGN KEY(dept_id) REFERENCES department(dept_id)
)

You need a table with 2 fields; person_id and dept_id. The table will have foreign keys to the two tables person and department primary keys' and a composite primary key of both.

Also, this table is only necessary if there is a one to many relationship of person to department. Otherwise just add dept_id as a foreign key in person.

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