mysql复合主键做外键,使用复合主键作为外键

How can I use a composite primary key as a foreign key? It looks like my attempt does not work.

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) )

解决方案

The line:

FOREIGN KEY (pk_studentID ) REFERENCES student(pk_studentID ),

is wrong. You can't use pk_studentID like that, this is just the name of the PK constraint in the parent table. To use a compound Primary Key as Foreign Key, you'll have to add the same number of columns (that compose the PK) with same datatypes to the child table and then use the combination of these columns in the FOREIGN KEY definition:

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 ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值