如何在SQL中复制1-m关系的条目

时间:2017-01-19 23:26:47

标签: mysql sql

我建立了一个可以拥有 m 种专业知识的律师。 然后我的框架生成了这3个表:

  1. 律师
  2. lawyer_expertise_mm
  3. 鉴定
  4. 示例:

    Lawyer

    id, name, email, expertises(amount)  
    - 1, Joe, joe@joe.com, 2
    

    Expertise

    id, name  
    - 1, Employee rights
    - 2, Information safety
    

    lawyer_expertise_mm包含以下列:

    id_local(lawyer), id_foreign(expertise)  
    - 1, 1
    - 1, 2
    

    现在我想复制所有律师并将他们的电子邮件更改为一个地址用于测试。问题是,在我这样做之后,所有副本都不具备任何专业知识,因为我的sql只将副本插入律师表中:

    INSERT INTO `Lawyer`
    ( `name`, `email`,`expertises`)
    SELECT  `name`, "test@test.test",`expertises`
    FROM Lawyer
    

    我不知道如何编写一个sql语句,该语句也会在lawyer_expertise_mm中为新律师的ID复制。
    所以我得到的是:

    id, name, email, expertises
    - 1, Joe, joe@joe.com, 2
    - 2, Joe, test@test.test, 2
    

    但我缺少的是:

    id_local(lawyer), id_foreign(expertise)  
    - 1, 1
    - 1, 2
    - 2, 1
    - 2, 2
    

    那我怎么能做到这一点? (这似乎不符合我所做的事情,但那是因为我将我的例子分解为我的问题的基础,我只是想知道是否有一个很好的方法来做到这一点我还不知道)

    我正在使用phpMyAdmin。

2 个答案:

答案 0 :(得分:1)

将其视为伪代码。我不确定我是否正确使用了所有MySQL函数/语法。

update Lawyer /* make the names unique */
set name = name + right('000000' + cast(id as varchar(6)), 6)

select max(id) from Lawyers /* use this value in the query below */

<copy lawyers here> /* copies will have the same name */

insert into lawyer_expertise_mm (id, expertise)
select l2.id, le.expertise
from
    Lawyer l1
    inner join lawyer_expertise_mm le
        on le.id_foreign = l1.id
    inner join Lawyer l2 /* link up the attorneys by range and name */
        on l1.id <= <max_id> and l2.id > <max_id> and l2.name = l1.name

update Lawyer /* revert to the original names */
set name = left(name, char_length(name) - 6)

答案 1 :(得分:0)

创建“临时”列origin_id,以便在复制id表中的条目时存储原始Lawyer。然后,您可以在联接中使用它来查找和复制lawyer_expertise_mm表中的相关条目。

alter table Lawyer add column origin_id int default null;

INSERT INTO `Lawyer`
( `name`, `email`,`expertises`, origin_id)
SELECT  `name`, "test@test.test",`expertises`, id
FROM Lawyer;

insert into lawyer_expertise_mm
    select l.id, mm.id_foreign
    from lawyer_expertise_mm mm
    join Lawyer l on l.origin_id = mm.id_local;

alter table Lawyer drop column origin_id;

http://rextester.com/FURWK58495