简体   繁体   中英

Relation between tables

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


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

so what I want to do is, If I execute the query below,

DELETE Person WHERE PersonId = 1

SQL should not allow me to delete from Person table since there are rows related to that Person in Address table.

How can I create this relation?

You need to define a foreign key:

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

Add a foreign key constraint and restrict deletes:

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?

You can try this:

DELETE Address WHERE PersonId = 1

after that

DELETE Person WHERE PersonId = 1

or you can reference in Address table

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

The PersonId of Person should be PRIMARY KEY and PersonId of Address table should be FOREIGN KEY which should REFERENCE PersonId of Person . If this relation exists between these two tables, then automatically the DBMS will return error on deleting a record from Person table if the ID exists in Address table.

The below SQL will alter your tables.

ALTER TABLE Persons
ADD PRIMARY KEY (PersonId)

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

Try this,this will solve your case

SQL should not allow me to delete from Person table since there are rows related to that Person in Address table

 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

You can create primary key and foreign key relationships in these tables, this will prevent deleteing records from Person if there are corresponding entries in Address table.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM