【问题标题】:MYSQL inserting records form table A into tables B and C (linked by foreign key) depending on column values in table AMYSQL根据表A中的列值将表A的记录插入表B和C(由外键链接)
【发布时间】:2011-06-05 14:40:08
【问题描述】:

一直在寻找解决mysql插入问题的简单方法。问题如下:

我正在整理一个由部门和办公桌组成的组织数据库。一个部门可能有也可能没有 n 个办公桌。

部门和服务台都有自己的表,通过服务台中的外键链接到部门中的相关记录(即 pk)。我有一个临时表,我用它来放置所有新的部门数据(长 n 条记录)......在这个表中,一个部门的 n 条办公桌记录跟在下面的部门记录后面。在 TEMP 表中,如果列 department_name 有值,则为部门,如果没有,则列desk 有值,因此将是与上述部门相关的办公桌。正如我所说,在您获得下一个部门记录之前,可能有几份办公桌记录。

这是表格记录的示例

TEMP{Department,Desk main_telephone, telephone2, telephone3, email, email2, website}

departments(department, telephone1, telephone2, telephone3, email, email2, website)

desks(Desk, foreignkey=Department id, telephone1, telephone2, telephone3, email, email2, website) 

好的,所以我想做的是:

从 TEMP 中,将部门插入到部门表中,将他们的办公桌插入到办公桌表中,在办公桌记录中生成一个外键到相关部门 id。

这是我目前拥有的

INSERT INTO departments(department,main_telephone,telephone2,telephone3,main_fax,website,email,email2)

SELECT Department,Tel1, Tel2, Tel3, Fax, Email, Email2, Web 
  FROM temp WHERE Department != '';

SELECT @last_department := LAST_INSERT_ID();

INSERT INTO department_desks(department_id,department, telephone, extension, telephone2, extension2, telephone3, extension3, fax, email)

SELECT @last_department, Desk,Tel1, Ext1, Tel2, Ext2, Tel3, Ext3,Fax, Email
  FROM temp WHERE Desk != '';

除了 last_insert_id 返回在上述 INSERT INTO 语句中生成的第一个 id 之外,此方法有效,因此所有办公桌都具有相同的部门 ID,我需要相对于部门的 id...

在伪代码中:

for each record in TEMP table
if Department
   INSERT the record into Departments
   get the id of the newly created Department record and store it somewhere
else if Desk
   INSERT the desk into the desks table with the relevant departments id as the foreignkey

再次注意,所有部门的办公桌都直接跟随 TEMP 表中的部门

非常感谢

【问题讨论】:

    标签: mysql select insert foreign-keys conditional


    【解决方案1】:

    好的,找到了解决方案。我将不得不创建一个存储过程并使用游标。我会报告我的进展。

    【讨论】:

      【解决方案2】:

      表 A { id、dept、desk }

      表 B { id, foreignkey, dept }

      insert into B (id, foreignkey, dept) select null, id, dept from A;

      【讨论】:

      • 假设 id 是 auto_increment 字段
      • 是的,抱歉,id 是自动递增的。在上面的示例中,表 B 中有一个外键。在我的示例中,表 B 是部门表,表 C 是办公桌表。我想测试表 A 中的列,如果一个部门将其粘贴到部门中,并且如果它后面有桌子,则将它们粘贴在桌子上,并带有表 B 中部门记录的外键
      猜你喜欢
      • 2015-05-12
      • 2016-09-21
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多