将值插入从父表引用的子表中

时间:2014-09-14 11:46:11

标签: mysql parent-child composite-primary-key insert-into junction-table

昨晚我试图解决这个问题,但没有运气,所以我希望你们可以提供帮助,因为我想出了所有的想法:

我有两个父表,我想从中填充一个Junction表:

新娘:

create table if not exists `Brides` ( 
    `BrideID` INT not null auto_increment,
    `MaidenName` varchar(10) unique,
    primary key (`BrideID`)
   ) engine=InnoDB;

    insert into Brides (MaidenName)
    values ('Smith'),
           ('Jones')
    ;

教会:

create table if not exists `Churches` (
`ChurchID` INT not null auto_increment,
`ChurchName` varchar(10) unique,
primary key (`ChurchID`)
) engine=InnoDB;

insert into Churches (ChurchName)
values ('St Marys'),
       ('St Albans')
;

我试图通过间接引用每个父表中的唯一名称来填充Junction表 Marriages 的ID变量。此外,我希望包含MarriedName以确定新娘是否结婚不止一次:

婚姻:

create table if not exists 'Marriages' (
'BrideID' INT not null,
'ChurchID' INT not null,
'MarriedName' TEXT not null
primary key ('BrideID','ChurchID','MarriedName')
  INDEX `fk_Marriages_Brides1_idx` (`BrideID` ASC),
  INDEX `fk_Marriages_Churches1_idx` (`ChurchID` ASC),
  CONSTRAINT `fk_Marriages_Brides1`
    FOREIGN KEY (`BrideID`)
    REFERENCES `Brides` (`BrideID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Marriages_Churches1`
    FOREIGN KEY (`Church_ID`)
    REFERENCES `Churches` (`ChurchID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
;   

我尝试做类似下面的伪代码(虽然我很确定它无论如何都不是聪明的方法,因为必须要有这么多的子-queries):

insert into Marriages (Bride_ID, Church_ID, MarriedName)
  select b.BrideID, c.ChurchID, m.MarriedName
  from (values (Bride,Church,MarriedName)
         ('Smith','St Marys','Johnson'),
         ('Jones','St Albans','Peterson')
         ) m

  join Brides b
  on a.MaidenName=m.Bride
  join Churches c
  on m.Church=c.ChurchName;

非常感谢您的任何帮助/见解/更正!

2 个答案:

答案 0 :(得分:1)

尝试一下:

INSERT INTO Marriages
SELECT b.BrideID, c.ChurchID, 'Johnson'
FROM Brides b, Churches c
WHERE b.MaidenName='Smith' AND c.ChurchName='St Marys'

答案 1 :(得分:0)

为了完整起见,我想分享这个解决方案,以防它帮助其他人......第一步也是最后一步不需要改变,只需要原始的'第二步中的数据需要添加到:

create table if not exists `_marriages` (
  `BrideName` varchar(10) null,
  `ChurchName` varchar(10) null,
  `MarriedName` varchar(10)  NULL,
 primary key (`BrideName`,`ChurchName`,`MarriedName`))
 engine=InnoDB
;

insert into `_marriages` (BrideName,ChurchName,MarriedName)
  values 
    ('Smith','St Albans','Johnson'),
    ('Jones','St Marys','Peterson')
;

insert into `Marriages` (Bride_ID, Church_ID, MarriedName)
select distinct b.BrideID, c.ChurchID, a.MarriedName
from _marriages a
inner join Brides b
  on (a.BrideName=b.MaidenName)
left join Churches c
  on a.ChurchName=c.ChurchName
;

...一如既往,如果有人在更好的方式上取得任何进展,请告诉我们!