我有一张这种结构的桌子(简化版):

artID: 1
artName: TNT
ArtBrand: ACME
...

我想将它规范化,为品牌创建一个单独的表(它将有关于每个品牌的额外数据)
所以我想以这个结束
物品表:
artID: 1
artName: TNT
brandID: 1
...

品牌表
brandID: 1
brandName: ACME
brandInfo: xyz
....

这张桌子的牌子太多了,不能手动操作。
有什么简单的自动化方法吗?
我在用mysql

最佳答案

正如其他答案所建议的,您可以使用INSERT ... SELECT语法执行以下操作:

INSERT INTO brands (brandName)
SELECT   artBrand
FROM     original
GROUP BY artBrand;

INSERT INTO articles (artName, brandID)
SELECT   o.artName, b.brandID
FROM     original o
JOIN     brands b ON (b.brandName = o.artBrand);

测试用例:
CREATE TABLE original (artID int, artName varchar(10), artBrand varchar(10));
CREATE TABLE articles (artID int auto_increment primary key, artName varchar(10), brandID int);
CREATE TABLE brands (brandID int auto_increment primary key, brandName varchar(10));

INSERT INTO original VALUES (1, 'TNT1', 'ACME1');
INSERT INTO original VALUES (2, 'TNT2', 'ACME1');
INSERT INTO original VALUES (3, 'TNT3', 'ACME1');
INSERT INTO original VALUES (4, 'TNT4', 'ACME2');
INSERT INTO original VALUES (5, 'TNT5', 'ACME2');
INSERT INTO original VALUES (6, 'TNT6', 'ACME3');
INSERT INTO original VALUES (7, 'TNT7', 'ACME3');
INSERT INTO original VALUES (8, 'TNT8', 'ACME3');
INSERT INTO original VALUES (9, 'TNT9', 'ACME4');

结果:
SELECT * FROM brands;
+---------+-----------+
| brandID | brandName |
+---------+-----------+
|       1 | ACME1     |
|       2 | ACME2     |
|       3 | ACME3     |
|       4 | ACME4     |
+---------+-----------+
4 rows in set (0.00 sec)


ELECT * FROM articles;
+-------+---------+---------+
| artID | artName | brandID |
+-------+---------+---------+
|     1 | TNT1    |       1 |
|     2 | TNT2    |       1 |
|     3 | TNT3    |       1 |
|     4 | TNT4    |       2 |
|     5 | TNT5    |       2 |
|     6 | TNT6    |       3 |
|     7 | TNT7    |       3 |
|     8 | TNT8    |       3 |
|     9 | TNT9    |       4 |
+-------+---------+---------+
9 rows in set (0.00 sec)

关于mysql - 自动化表格标准化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3082527/

10-11 00:40