创建表

AJM*_*AJM 1 sql oracle sqlplus

假设您有以下数据库:

Person(ssn NUMERIC(9), name VARCHAR(40), gender CHAR(1)), ssn is primary key

Organization(org_code CHAR(4), budget INTEGER, org_name VARCHAR(60)), org_code is primary key

Person_Organization(ssn, org_code), both columns are the primary key.
Run Code Online (Sandbox Code Playgroud)

person_organization表中的键是否被视为外键或主键?我被困在如何创建这个表.尝试查看我的教科书但无法找到有关它的信息.我不知道它们是否应该是引用主键的外键,或者我应该这样做

CREATE TABLE person_organization(ssn NUMERIC(9), org_code VARCHAR(60));
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激.

谢谢.

Ben*_*Ben 5

简单的答案是他们都是.

ssn, org_code应该是主要的关键person_organization.

ssn应该是外键重新回到人,org_code应该通过外键重新进入organization.

为了将自己与northpole的答案分开,我实际上并不同意代理键参数在这种情况下似乎不需要它,因为它不会在其他任何地方使用.

不幸的是这个(好)解决了多对多的关系问题是,它往往需要有一个表中的两个独特的按键,ssn, org_code 以及 org_code, ssn并选择一个作为主键.


当您使用Oracle时,create table语法就是

create table person_organization
( ssn number(9)
, org_code varchar2(60)
, constraint person_organization_pk primary key (ssn, org_code)
, constraint person_organization_ssn_fk foreign key ( ssn )
    references person ( ssn )
, constraint person_organization_oc_fk foreign key ( org_code )
    references organization ( org_code )
 );
Run Code Online (Sandbox Code Playgroud)

在原始的表创建脚本中,您应该使用ssnas .您可能需要考虑不限制此数据类型的大小.你也有作为,这或许应该是一个.numeric(9)number(9)org_codevarcharvarchar2

Tech on the Net是学习语法的非常好的资源.