MySQL外键实现

时间:2013-11-07 16:18:29

标签: mysql

我是MySQL的新手,我有两个名为Person&的表。患者。我正在尝试在Patient中创建一个简单的外键关系到Person中的主键。我在网上看到的所有例子都遵循我正在使用的相同结构,但我一直都会遇到错误。非常感谢任何帮助!

create table PERSON(
    PatientID smallint UNSIGNED NOT NULL,
    Firstname varchar (25),
    Lastname varchar (25),
    CONSTRAINT PatientID_pk PRIMARY KEY (PatientID)
);

这个表我正在尝试添加一个外键:

CREATE TABLE PATIENT(
    PatientID smallint UNSIGNED NOT NULL, 
    DoctorID smallint UNSIGNED NOT NULL,
    FOREIGN KEY (PatientID) REFERENCES PERSON(PatientID);

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的

create table PERSON
(
  PersonID smallint UNSIGNED NOT NULL AUTO_INCREMENT,
  Firstname varchar (25),
  Lastname varchar (25),
  CONSTRAINT PersonID_pk PRIMARY KEY (PersonID)
);

CREATE TABLE PATIENT
(
  PatientID smallint UNSIGNED NOT NULL, 
  DoctorID smallint UNSIGNED NOT NULL,
  FOREIGN KEY (PatientID) REFERENCES PERSON(PersonID),
  FOREIGN KEY (DoctorID) REFERENCES PERSON(PersonID),
  UNIQUE KEY unique_key (PatientID, DoctorID)
);