关系SQL

时间:2017-12-13 15:49:44

标签: sql sql-server

我目前正在使用SQL Server进行项目。我不太熟悉这种编程语言,我需要建立关系。我创建的关系是

  • 宠物/主人(一对多)
  • 宠物/约会(一对一)
  • 约会/兽医(一对一)。

我查看了Google和YouTube,我认为我的代码是正确的。

在我开始添加数据之前,有人可以仔细检查我的工作吗?

CREATE TABLE Vet
(
     [VET_NUM] CHAR(5) PRIMARY KEY,
     [LAST_NAME] CHAR(20),
     [FIRST_NAME] CHAR(20),
     [STREET] CHAR(30),
     [CITY] CHAR(20),
     [STATE] CHAR(20),
     [POSTAL_CODE] CHAR(20),
     [SALARY] DECIMAL(8,2),
     [DEGREE] CHAR(20),
     [POSITION] CHAR(20)
);

CREATE TABLE Owner
(
     [OWNER_NUM] CHAR(20) PRIMARY KEY,
     [OWNER_NAME] CHAR(30) NOT NULL,
     [STREET] CHAR(30),
     [CITY] CHAR(20),
     [STATE] CHAR(20),
     [POSTAL_CODE] CHAR(20),
     [PET_NUM] CHAR(5)
);

CREATE TABLE Appointment
(
     [APPOINTMENT_NUM] CHAR(5) PRIMARY KEY,
     [APPOINTMENT_DATE] DATE,
     [VET_NUM] CHAR(3)
     [PET_NUM] CHAR(3) 
);

CREATE TABLE Pet 
(
     [PET_NUM] CHAR(3) PRIMARY KEY,
     [PET_NAME] CHAR(35) NOT NULL,
     [STREET] CHAR(30),
     [CITY] CHAR(15),
     [STATE] CHAR(2),
     [POSTAL_CODE] CHAR(5),
     [BREED] CHAR(20),
     [OWNER_NUM] CHAR(3),
     [APPOINTMENT_NUM] CHAR(5) 
);

2 个答案:

答案 0 :(得分:1)

您需要添加外键以支持关系,例如:

ALTER TABLE Owner     
ADD CONSTRAINT FK_Owner_Pet FOREIGN KEY (PET_NUM)     
    REFERENCES Pet (PET_NUM)     
    ON DELETE CASCADE    
    ON UPDATE CASCADE    
;    
GO

这实现了一对多的关系。

我不认为你真的想要一对一的关系。 PET只会有一个任命吗? VET只会有一个任命吗?

答案 1 :(得分:0)

我修改了你的设计。请使用此

    USE[zz_CIS245_16]
GO

CREATE TABLE Vet
(
    [VET_NUM] INT IDENTITY(1,1) CONSTRAINT Pk_Vet_VetNum PRIMARY KEY,
    [LAST_NAME] CHAR(20),
    [FIRST_NAME] CHAR(20),
    [STREET] CHAR(30),
    [CITY] CHAR(20),
    [STATE] CHAR(20),
    [POSTAL_CODE] CHAR(20),
    [SALARY] DECIMAL(8,2),
    [DEGREE] CHAR(20),
    [POSITION] CHAR(20)
);


CREATE TABLE Owner
(
    [OWNER_NUM] INT IDENTITY(1,1) CONSTRAINT Pk_Owner_OwnerNum PRIMARY KEY,
    [OWNER_NAME] CHAR(30) NOT NULL,
    [STREET] CHAR(30),
    [CITY] CHAR(20),
    [STATE] CHAR(20),
    [POSTAL_CODE] CHAR(20)
    --[PET_NUM] CHAR(5) -- Removed as duplicate (Owner Num already exists in Pet)
);


CREATE TABLE Pet
(
    [PET_NUM] INT IDENTITY(1,1) CONSTRAINT Pk_Pet_PetNum PRIMARY KEY,
    [PET_NAME] CHAR(35) NOT NULL,
    [STREET] CHAR(30),
    [CITY] CHAR(15),
    [STATE] CHAR(2),
    [POSTAL_CODE] CHAR(5),
    [BREED] CHAR(20),
    [OWNER_NUM] INT CONSTRAINT Fk_Pet_OwnerNum FOREIGN KEY REFERENCES Owner(OWNER_NUM),-- Added Foreign key reference 
    [APPOINTMENT_NUM] CHAR(5) 
)

CREATE TABLE Appointment
(
    [APPOINTMENT_NUM] INT IDENTITY(1,1) CONSTRAINT Pk_Appointment_AppointmentNum PRIMARY KEY,
    [APPOINTMENT_DATE] DATE,
    [VET_NUM] INT UNIQUE NOT NULL CONSTRAINT Fk_Appointment_VetNum FOREIGN KEY REFERENCES VET(VET_NUM),-- Added Foreign key reference  );
    [PET_NUM] INT UNIQUE NOT NULL CONSTRAINT Fk_Appointment_PetNum FOREIGN KEY REFERENCES Pet(PET_NUM)-- Added Foreign key reference  );
)