【问题标题】:Use Composite Primary Key as Foreign Key使用复合主键作为外键
【发布时间】:2012-05-20 21:43:42
【问题描述】:

如何使用复合主键作为外键?看来我的尝试不起作用。

create table student
(
student_id varchar (25) not null ,
student_name varchar (50) not null ,
student_pone int ,
student_CNIC varchar (50),
students_Email varchar (50),
srudents_address varchar(250),
dept_id varchar(6),
batch_id varchar(4),
FOREIGN KEY (dept_id) REFERENCES department(dept_id),
FOREIGN KEY (batch_id) REFERENCES batch(batch_id),
CONSTRAINT pk_studentID PRIMARY KEY (batch_id,dept_id,student_id) )

create table files
(
files_name varchar(50) not null ,
files_path varchar(50),
files_data varchar(max),
files_bookmarks xml ,
FOREIGN KEY (pk_studentID ) REFERENCES student(pk_studentID ),
CONSTRAINT pk_filesName PRIMARY KEY (files_name) )

【问题讨论】:

  • 如何使用复合主键作为外键
  • @Paul Bellora 我添加了问题。

标签: mysql sql oracle constraints


【解决方案1】:

行:

FOREIGN KEY (pk_studentID ) REFERENCES student(pk_studentID ),

错了。不能这样使用pk_studentID,这只是父表中PK约束的名称。要将复合主键用作外键,您必须将具有相同数据类型的相同数量的列(组成 PK)添加到子表中,然后在 FOREIGN KEY 定义中使用这些列的组合:

CREATE TABLE files
(
  files_name varchar(50) NOT NULL, 

  batch_id varchar(4) NOT NULL,         --- added, these 3 should not
  dept_id varchar(6) NOT NULL,          --- necessarily be NOT NULL
  student_id varchar (25) NOT NULL,     --- 

  files_path varchar(50),
  files_data varchar(max),              --- varchar(max) ??   
  files_bookmarks xml,                  --- xml ??
                                        --- your question is tagged MySQL, 
                                        --- and not SQL-Server

  CONSTRAINT pk_filesName 
    PRIMARY KEY (files_name),

  CONSTRAINT fk_student_files                     --- constraint name (optional)
    FOREIGN KEY (batch_id, dept_id, student_id)  
      REFERENCES student (batch_id, dept_id, student_id)
) ENGINE = InnoDB ;

【讨论】:

  • 另外,顺序很重要。
  • 你为我省去了很多的麻烦;这在文档中真的不清楚。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-07-24
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
相关资源
最近更新 更多