Populate many-to-many person-color table using three tables in MySQL(在MySQL中使用三个表填充多对多人-颜色表)
本文介绍了在MySQL中使用三个表填充多对多人-颜色表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在MySQL中规范化一个表,将一个具有许多相似列的表转换为具有两个列的多对多关系。我有以下表格:
人员:
+----+------+
| id | name |
+----+------+
| 1 | John |
| 2 | Anna |
| 3 | Leon |
+----+------+
Person_Temp:
+------+--------+--------+--------+--------+
| name | color1 | color2 | color3 | color4 |
+------+--------+--------+--------+--------+
| John | red | blue | green | |
| Anna | green | yellow | | |
| Leon | blue | red | | |
+------+--------+--------+--------+--------+
颜色:
+----+--------+
| id | name |
+----+--------+
| 1 | red |
| 2 | blue |
| 3 | green |
| 4 | yellow |
+----+--------+
我想在填充多对多关系表后删除PERSON_TEMP:
人色:
+-----------+----------+
| person_id | color_id |
+-----------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 2 | 4 |
| 3 | 2 |
| 3 | 1 |
+-----------+----------+
但是,我还没有找到我的查询的任何解决方案。我与人员ID的唯一关系是Person_Temp中的名称。我知道姓名在人称中是唯一的,因此使用它们进行查询不成问题。
我尝试使用此SQL,但它不起作用,因为Person_Temp没有id列。
INSERT INTO `person_color`
SELECT p.id, c.id
FROM (
SELECT id, color1 color
FROM person_temp
UNION
SELECT id, color2 FROM person_temp
UNION
SELECT id, color3 FROM person_temp
UNION
SELECT id, color4 FROM person_temp
UNION
SELECT id, color5 FROM person_temp
) p
JOIN color c
ON c.name = p.color;
推荐答案
您的原始查询简单明了。除了从person_temp
中选择name
而不是id
,您只需将name
与id
中的id
连接在一起。您不需要单独对person_temp
执行所有这些联接。
INSERT INTO person_color
SELECT p.id AS person_id, c.id AS color_id
FROM (
SELECT name, color1 AS color FROM person_temp
UNION
SELECT name, color2 FROM person_temp
UNION
SELECT name, color3 FROM person_temp
UNION
SELECT name, color4 FROM person_temp
UNION
SELECT name, color5 FROM person_temp
) nc
JOIN color c
ON c.name = nc.color
JOIN person p
ON p.name = nc.name;
表行没有顺序,因此在插入中ORDER BY p.id, c.id
是没有意义的。输出行有顺序。
这篇关于在MySQL中使用三个表填充多对多人-颜色表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:在MySQL中使用三个表填充多对多人-颜色表


基础教程推荐
猜你喜欢
- oracle区分大小写的原因? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01