[英]How to copy entries with 1-m relation in SQL
我模仿一個律師,可以有m種專業知識。 然后,我的框架生成了以下3個表:
例:
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語句,該語句也可以在律師_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。
將此視為偽代碼。 我不確定我是否正確使用了所有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)
當您復制“ Lawyer
表中的條目時,創建一個“臨時”列origin_id
來存儲原始id
。 然后,您可以在lawyer_expertise_mm
中使用它,以查找和復制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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.