Bidirectional foreign key constraint

前端 未结 6 1275
时光说笑
时光说笑 2020-12-19 07:33

I\'m thinking of designing a database schema similar to the following:

Person (
  PersonID int primary key,
  PrimaryAddressID int not null,
  ...
)

Address         


        
6条回答
  •  误落风尘
    2020-12-19 08:28

    I know I'll probably be crucified or whatever, but here goes...

    I've done it like this for my "particular very own unique and non-standard" business need ( =( God I'm starting to sound like SQL DDL even when I speak).

    Here's an exaxmple:

    CREATE TABLE IF NOT EXISTS PERSON(
        ID INT, 
        CONSTRAINT PRIMARY KEY (ID), 
        ADDRESS_ID INT NOT NULL DEFAULT 1, 
        DESCRIPTION VARCHAR(255), 
        CONSTRAINT PERSON_UQ UNIQUE KEY (ADDRESS_ID, ...));
    
    INSERT INTO PERSON(ID, DESCRIPTION) 
        VALUES (1, 'GOVERNMENT');
    
    CREATE TABLE IF NOT EXISTS ADDRESS(
        ID INT, 
        CONSTRAINT PRIMARY KEY (ID), 
        PERSON_ID INT NOT NULL DEFAULT 1, 
        DESCRIPTION VARCHAR(255), 
        CONSTRAINT ADDRESS_UQ UNIQUE KEY (PERSON_ID, ...), 
        CONSTRAINT ADDRESS_PERSON_FK FOREIGN KEY (PERSON_ID) REFERENCES PERSON(ID));
    
    INSERT INTO ADDRESS(ID, DESCRIPTION) 
        VALUES (1, 'ABANDONED HOUSE AT THIS ADDRESS');
    
    ALTER TABLE PERSON ADD CONSTRAINT PERSON_ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS(ID);
    

    <...life goes on... whether you provide and address or not to the person and vice versa>

    I defined one table, then the other table referencing the first and then altered the first to reflect the reference to the second (which didn't exist at the time of the first table's creation). It's not meant for a particular database; if I need it I just try it and if it works then I use it, if not then I try to avoid having that need in the design (I can't always control that, sometimes the design is handed to me as-is). if you have an address without a person then it belongs to the "government" person. If you have a "homeless person" then it gets the "abandoned house" address. I run a process to determine which houses have no users

提交回复
热议问题