MySQL复制记录多对多加入

时间:2016-06-29 13:50:34

标签: php mysql sql stored-procedures many-to-many

我在MySQL中有多对多连接将角色链接到任务(三个表:角色,任务和角色_任务)。每个角色和任务都属于一个项目。

Roles Table
id | project_id | role
---|------------|-------------
1  | 1          | Supervisor
2  | 1          | Manager

Tasks Table
id | project_id | task
---|------------|-------------
1  | 1          | Do this
2  | 1          | Do that

role_task Table
role_id | task_id
-----------------
1       | 1
1       | 2
2       | 1

我正在寻找一种纯SQL方法来将角色,任务及其关联的多对多连接从一个项目复制到另一个项目。我想要完成的是:

Roles Table
id | project_id | role
---|------------|-------------
1  | 1          | Supervisor
2  | 1          | Manager
3  | 2          | Supervisor
4  | 2          | Manager

Tasks Table
id | project_id | task
---|------------|-------------
1  | 1          | Do this
2  | 1          | Do that
3  | 2          | Do this
4  | 2          | Do that

role_task Table
role_id | task_id
--------|--------
1       | 1
1       | 2
2       | 1
3       | 3
3       | 4
4       | 3

我可以在Roles表和Tasks表中复制/复制数据而不会出现问题。但是,如何使用新的角色ID和任务ID复制role_task表?我可以在PHP中使用循环并抓取插入的id,但更喜欢纯SQL解决方案。感谢

2 个答案:

答案 0 :(得分:1)

我能够做到这一点的唯一合理方法是在Roles and Tasks表中添加一个保存原始记录ID的字段。 role_task表保持不变,但我的其他两个表现在看起来像这样:

roles table
id | project_id | original_id | role
---|------------|-------------|-----
1  | 1          | 0           | Supervisor
2  | 1          | 0           | Manager

tasks table
id | project_id | original_id | task
---|------------|-------------|-----
1  | 1          | 0           | Do this
2  | 1          | 0           | Do that

因此,将角色和任务复制到project_id为3的SQL是:

INSERT roles
SELECT NULL, 3, id, role FROM Roles WHERE project_id = 1

INSERT tasks
SELECT NULL, 3, id, task FROM Tasks WHERE project_id = 1

然后,复制多对多表:

INSERT role_task
SELECT r.id, t.id
FROM role_task AS rt
LEFT JOIN roles AS r ON rt.role_id = r.original_id
LEFT JOIN tasks AS t ON rt.task_id = t.original_id
WHERE  r.project_id = 3
AND    t.project_id = 3

答案 1 :(得分:0)

提供任务和角色表是自动递增的,您可以执行以下操作......

注意我使用了3作为project_id,但这可以是从数据库中的另一个表中查找..

INSERT INTO tasks (project_id, task) SELECT DISTINCT 3 ,`task` FROM `tasks`;

INSERT INTO roles (project_id, role) SELECT DISTINCT 3,`role` FROM `roles`;

INSERT INTO role_tasks (task_id, role_id) SELECT tasks.id AS task_id, roles.id AS role_id FROM `tasks` CROSS JOIN `roles`  WHERE tasks.project_id=3 AND roles.project_id=3