如何对重复 mysql 数据进行非规范化?
How to a denormalize repeating mysql data?
你好,我需要对 MySQL table 和重复数据进行一些反规范化。
我的"Publications"table目前是这种格式:
Publications Source Table
| title | author
--------------------------------------------
| my paper | michael
| my paper | bill
| my paper | jill
| other paper | tom
| other paper | amy
| third paper | ben
| third paper | sophie
我需要将其更改为这种格式:
Publications Destination Table
| title | author | author2 | author 3
|-----------------------------------------------------------------
| my paper | michael | bill | jill
| other paper | tom | amy |
| third paper | ben | sophie |
现在,仅供参考,我需要这样做,以便我最终可以获得一个 CSV 文件,以便可以将数据从旧系统导出到需要这种格式的 CSV 文件的新系统中。
table 中还有许多其他字段,源 table 中有大约 60,000 行,但只有大约 15,000 个唯一标题。在来源 table 中,每位作者一行。在目标中,title 将是唯一标识符。每个唯一的出版物标题我需要一行。我也可以提前计算任何一份出版物上最多的作者人数,如果这样可以使问题更容易的话。
如何在 MySQL 中执行此操作?谢谢
我的建议是您实际上规范化 table 而不是为补充作者添加新列。所以你的新 table 结构看起来像这样:
Publications Source Table
| title_id | title
--------------------------------------------
| 1 | my paper
| 2 | other paper
| 3 | third paper
| title_id | author
--------------------------------------------
| 1 | michael
| 1 | bill
| 1 | jill
| 2 | tom
| 2 | amy
| 3 | ben
| 3 | sophie
如果您实际上不想改变 table 的结构,而只是想取出数据以便将其导入新系统,您可以尝试 GROUP_CONCAT() 函数在 mysql:
SELECT title, GROUP_CONCAT(author SEPARATOR "|") AS authors FROM publications GROUP BY title;
我使用竖线作为分隔符,因为您的标题很可能包含逗号。如果你希望它最终成为一个 csv 文件,你可以在管道字符上做一个 find-and-replace 来把它变成它需要的任何东西(例如,", "
)。
你好,我需要对 MySQL table 和重复数据进行一些反规范化。
我的"Publications"table目前是这种格式:
Publications Source Table
| title | author
--------------------------------------------
| my paper | michael
| my paper | bill
| my paper | jill
| other paper | tom
| other paper | amy
| third paper | ben
| third paper | sophie
我需要将其更改为这种格式:
Publications Destination Table
| title | author | author2 | author 3
|-----------------------------------------------------------------
| my paper | michael | bill | jill
| other paper | tom | amy |
| third paper | ben | sophie |
现在,仅供参考,我需要这样做,以便我最终可以获得一个 CSV 文件,以便可以将数据从旧系统导出到需要这种格式的 CSV 文件的新系统中。
table 中还有许多其他字段,源 table 中有大约 60,000 行,但只有大约 15,000 个唯一标题。在来源 table 中,每位作者一行。在目标中,title 将是唯一标识符。每个唯一的出版物标题我需要一行。我也可以提前计算任何一份出版物上最多的作者人数,如果这样可以使问题更容易的话。
如何在 MySQL 中执行此操作?谢谢
我的建议是您实际上规范化 table 而不是为补充作者添加新列。所以你的新 table 结构看起来像这样:
Publications Source Table
| title_id | title
--------------------------------------------
| 1 | my paper
| 2 | other paper
| 3 | third paper
| title_id | author
--------------------------------------------
| 1 | michael
| 1 | bill
| 1 | jill
| 2 | tom
| 2 | amy
| 3 | ben
| 3 | sophie
如果您实际上不想改变 table 的结构,而只是想取出数据以便将其导入新系统,您可以尝试 GROUP_CONCAT() 函数在 mysql:
SELECT title, GROUP_CONCAT(author SEPARATOR "|") AS authors FROM publications GROUP BY title;
我使用竖线作为分隔符,因为您的标题很可能包含逗号。如果你希望它最终成为一个 csv 文件,你可以在管道字符上做一个 find-and-replace 来把它变成它需要的任何东西(例如,", "
)。