Best MySQL Table Structure: 2 Parents, 1 Child

后端 未结 2 1390
情歌与酒
情歌与酒 2021-01-23 18:44

I have two parent tables, BusinessGroup and SocialGroup, and one child table, Members. A Member can belong to either parent, but not both.

As far as I can see, there ar

相关标签:
2条回答
  • 2021-01-23 18:49

    CREATE TABLE Group ( 
        GroupID       integer    NOT NULL
      , Name          varchar(18)
      , Description   varchar(18)
      , GroupType     varchar(4) NOT NULL
      -- all columns common to any group type
    );
    ALTER TABLE Group ADD CONSTRAINT pk_Group PRIMARY KEY (GroupID) ;
    
    
    CREATE TABLE BusinessGroup ( 
        GroupID   integer NOT NULL
      -- all columns specific to business groups
    );
    ALTER TABLE BusinessGroup
        ADD CONSTRAINT pk_BusinessGroup  PRIMARY KEY (GroupID)
      , ADD CONSTRAINT fk1_BusinessGroup FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
    
    
    CREATE TABLE SocialGroup ( 
        GroupID    integer NOT NULL
      -- all columns specific to social groups
    );
    ALTER TABLE SocialGroup
        ADD CONSTRAINT pk_SocialGroup  PRIMARY KEY (GroupID)
      , ADD CONSTRAINT fk1_SocialGroup FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
    
    
    CREATE TABLE Person ( 
        PersonID  integer NOT NULL
      , GroupID   integer NOT NULL
    );
    ALTER TABLE Person
        ADD CONSTRAINT pk_Person  PRIMARY KEY (PersonID)
      , ADD CONSTRAINT fk1_Person FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
    
    0 讨论(0)
  • 2021-01-23 18:49

    "parent tables" is probably a misnomer - in the relational model I'd flip your relationship. e.g. make members the master records table, and a join table that allows 1-1 mapping, so have a PK of member_id or whatever the right field is, and map to the FK in either BusinessGroup or SocialGroup.

    0 讨论(0)
提交回复
热议问题