表之间的关系

时间:2014-01-14 08:38:01

标签: sql

Person Table
-------------------------------------
PersonId   |   Name   |   Surname   |
-------------------------------------
1              John       Smith
2              Sam        Rainbow


Address Table
------------------------------------------
AddressId   |   PersonId   |   Address   |
------------------------------------------
1               1              AAA
2               1              BBB

所以我想做的是,如果我执行下面的查询,

DELETE Person WHERE PersonId = 1

SQL不应该允许我从Person表中删除,因为在Address表中有与Person相关的行。

如何创建此关系?

6 个答案:

答案 0 :(得分:3)

您需要定义外键:

ALTER TABLE Address
ADD FOREIGN KEY (PersonId)
REFERENCES Person (PersonId) 

答案 1 :(得分:1)

添加外键约束并限制删除:

ALTER TABLE Address
ADD CONSTRAINT Address_PersonId_fkey
FOREIGN KEY (PersonId)
REFERENCES Person (PersonId)
ON DELETE RESTRICT  -- what you asked for
ON UPDATE CASCADE;  -- maybe do something different for updates?

答案 2 :(得分:0)

你可以试试这个:

DELETE Address WHERE PersonId = 1

之后

DELETE Person WHERE PersonId = 1

或您可以在地址表中引用

ALTER TABLE Address
ADD FOREIGN KEY (PersonId)
REFERENCES Person (PersonId) 

答案 3 :(得分:0)

PersonId的{​​{1}}应为Person,而PRIMARY KEY表的PersonId应为Address FOREIGN KEYREFERENCE PersonId of Person如果这两个表之间存在这种关系,那么如果ID存在于Address表中,DBMS将自动返回从Person表中删除记录时的错误。

以下SQL将改变您的表格。

ALTER TABLE Persons
ADD PRIMARY KEY (PersonId)

ALTER TABLE Address
ADD FOREIGN KEY (PersonId)
REFERENCES Persons(PersonId)

答案 4 :(得分:0)

试试这个,这将解决你的情况

  

SQL不应该允许我从Person表中删除,因为有   与地址表中的该人相关的行

 DECLARE @CNT AS BIGINT
    SELECT @CNT=ISNULL(COUNT(PersonId),0) FROM Address where PersonId=1 


    IF @CNT=0
        BEGIN
            DELETE Person WHERE PersonId = 1
        END

答案 5 :(得分:0)

您可以在这些表中创建主键和外键关系,如果Address表中有相应的条目,这将防止从Person中删除记录。

CREATE TABLE Person
    (
    PersonId INT CONSTRAINT pk_person_pid PRIMARY KEY,
    Name VARCHAR(25),
    Surname VARCHAR(25)
    );


    CREATE TABLE Address
    (
    AddressId INT CONSTRAINT pk_address_aid PRIMARY KEY,
    PersonId INT CONSTRAINT fk_personAddress_pid FOREIGN KEY REFERENCES Person(PersonId),
    AddressVARCHAR(25)
    );

Reference: creating primary key, foreign key constraints