简体   繁体   English

SQL中两个表的交集

[英]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.例如,我有一个名为 person 的表,其中包含元素 person_id、first_name、last_name、gender、age 和 fav_quote。 I have a second table called department with the elements dept_id, dept_name, and building.我有一个名为部门的第二个表,其中包含元素 dept_id、dept_name 和 building。 I now need to create and intersection table with the person_id and dept_id elements included.我现在需要创建包含 person_id 和 dept_id 元素的交集表。 And both must be the primary key (which I assume just means PRIMARY KEY (person_id, dept_id) command in my source).并且两者都必须是主键(我假设在我的源代码中仅表示 PRIMARY KEY (person_id, dept_id) 命令)。

CREATE TABLE person (创建表人(

person_id INT(8) NOT NULL auto_increment, person_id INT(8) NOT NULL auto_increment,

first_name VARCHAR(25) NOT NULL, first_name VARCHAR(25) 非空,

last_name VARCHAR(25) NOT NULL, last_name VARCHAR(25) 非空,

gender VARCHAR(1),性别 VARCHAR(1),

age INT(8),年龄 INT(8),

fav_quote TEXT, fav_quote 文本,

PRIMARY KEY (person_id)主键 (person_id)

); );

CREATE TABLE department (创建表部门(

dept_id INT(8) NOT NULL auto_increment, dept_id INT(8) NOT NULL auto_increment,

dept_name VARCHAR(25) NOT NULL,部门名称 VARCHAR(25) 非空,

building VARCHAR(25) NOT NULL,构建 VARCHAR(25) NOT NULL,

PRIMARY KEY (dept_id)主键 (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;你需要一个有 2 个字段的表格; person_id and dept_id. person_id 和 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.否则只需亲自添加 dept_id 作为外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM