SQL Many-to-Many Relationship Between Multiple Tables

后端 未结 3 1160

I have a database I\'m trying to create on SQL and I am trying to connect the relationships together. There are three tables: superhero, power, and superheroPower. The tables su

3条回答
  •  鱼传尺愫
    2021-01-24 02:37

    Your design seems on the right track, this is the tables i would have gone with - adding some Indexes for the fields its likely that you will search for and adding the actions needed for the CONSTRAINT keys

    CREATE TABLE `_superhero` (
      `id` int(11) NOT NULL auto_increment,
      `heroName` varchar(255) NOT NULL,
      `firstName` varchar(255) default NULL,
      `lastName` varchar(255) default NULL,
      `firstAppearance` date default NULL,
      `gender` enum('Other','Female','Male') default NULL,
      `bio` text,
      `universe` varchar(255) default NULL,
      PRIMARY KEY  (`id`),
      KEY `indxHname` (`heroName`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    CREATE TABLE `_power` (
      `id` int(11) NOT NULL auto_increment,
      `name` varchar(255) NOT NULL,
      `description` text NOT NULL,
      PRIMARY KEY  (`id`),
      KEY `indx4` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    CREATE TABLE `_superheropower` (
      `superheroID` int(11) NOT NULL default '0',
      `powerID` int(11) NOT NULL default '0',
      PRIMARY KEY  (`superheroID`,`powerID`),
      KEY `indx1` (`superheroID`),
      KEY `indx2` (`powerID`),
      CONSTRAINT `fk2` FOREIGN KEY (`powerID`) REFERENCES `_power` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
      CONSTRAINT `fk1` FOREIGN KEY (`superheroID`) REFERENCES `_superhero` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

提交回复
热议问题