在MySQL中将n复制到m关系

时间:2019-05-17 18:15:08

标签: mysql foreign-keys entity-relationship

假设我有两个表recipientlistrecipient具有列idemailcustomer的列。 list具有列idnamecustomer的列。

两个表都通过recipient_list与列recipient_idlist_id连接。

recipientlist中,我都有customer“演示客户”的数据,并且在联接表中有相应的条目。

我现在要做的是将这些条目包括复制到另一位客户。我知道我可以使用以下模式使用select插入数据:

INSERT INTO table_name(column_list)
SELECT 
   select_list 
FROM 
   another_table;

这样,我可以复制recipientlist的条目。但是,这对我重复n-m关系没有帮助。我该如何实现?

编辑: 这是我想要实现的简短示例:

之前:

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 |
+--------------+---------+

之后:

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 |
+--------------+---------+

请注意,主键不一定像示例中那样好。

1 个答案:

答案 0 :(得分:0)

要插入的查询为

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

“另一个表”应该是customer_name上的收件人表和列表表的联接。加入会消除因n-m关系而引起的不良情况。