简体   繁体   中英

Copy n to m relation in MySQL

Suppose I habe two tables recipient and list . recipient has the columns id , email and customer . list has the columns id , name and customer .

Both tables are connected via recipient_list with the columns recipient_id and list_id .

In both recipient and list I have data for the customer "Demo customer" with appropriate entries in the join table.

What I'm trying to do now is to copy these entries including the relationship to another customer. I am aware I can insert data using a select using the following schema:

INSERT INTO table_name(column_list)
SELECT 
   select_list 
FROM 
   another_table;

With this I can copy the entries of recipient and list . However this does not help me with duplicating the nm relations. How can I achieve that?

Edit: Here's a short example of what I like to achieve:

Before:

recipient
+----+------------------+---------------+
| id |      email       |   customer    |
+----+------------------+---------------+
|  1 | test@example.org | Demo Customer |
+----+------------------+---------------+
list
+----+-----------+---------------+
| id |   name    |   customer    |
+----+-----------+---------------+
|  1 | demo list | Demo Customer |
+----+-----------+---------------+
recipient_list
+--------------+---------+
| recipient_id | list_id |
+--------------+---------+
|            1 |       1 |
+--------------+---------+

After:

recipient
+----+------------------+---------------+
| id |      email       |   customer    |
+----+------------------+---------------+
|  1 | test@example.org | Demo Customer |
|  2 | test@example.org | Real Customer |
+----+------------------+---------------+
list
+----+-----------+---------------+
| id |   name    |   customer    |
+----+-----------+---------------+
|  1 | demo list | Demo Customer |
|  2 | demo list | Real Customer |
+----+-----------+---------------+
recipient_list
+--------------+---------+
| recipient_id | list_id |
+--------------+---------+
|            1 |       1 |
|            2 |       2 |
+--------------+---------+

Please note that the primary keys aren't necessarily as nice as in the example.

The query to insert would be

INSERT INTO table_name(column_list)
SELECT 
   select_list 
FROM 
   another_table
WHERE customer = customer_name;

The "another_table" should be the join of recipient and list tables over customer_name. Taking join would eliminate the bad cases arising due to nm relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM