拆分表并正确重新插入所有数据

时间:2019-07-04 15:02:02

标签: mysql

问题

考虑表“存储的产品”

        |           ProductsStored               |
        ------------------------------------------
        | id | product | type      | description |
        ------------------------------------------
        | 1  |  AX     | Cleaning  | bla bla bla |
        | 2  |  AB     | Food      | bla bla bla |
        | 3  |  AJ     | Cleaning  | bla bla bla |
        | 4  |  KR     | Food      | bla bla bla |

我想将此表分为两部分:

|  ProductsType  |
-------------------
| id |  type     | 
------------------
| 1  | Cleaning  | 
| 2  | Food      | 


|           Products                   |
----------------------------------------
| id | product | idType  | description |
----------------------------------------
| 1  |  AX     | 1       | bla bla bla |
| 2  |  AB     | 2       | bla bla bla |
| 3  |  AJ     | 1       | bla bla bla |
| 4  |  KR     | 2       | bla bla bla |

我有几种使用此类表的模式。必须在新的两个表中插入数据并保持ID完整。

我想出了以下代码,但我遗漏了一部分:

插入产品类型

INSERT INTO `ProductsType` (id, type) SELECT DISTINCT `type` FROM `ProductsStored`

插入产品并通过“ ProductsType”与其类型建立联系

INSERT INTO `Products` (id, product, description, idType) SELECT id,product,description ...(how do I get the idType?) 

我不明白如何正确获取idType。另外,这种方法是正确的方法吗?

参考

How split data from table and insert to new relation?

这个主题几乎回答了我的问题,但是它使用了@rownr,我不明白他为什么这样做。而且似乎他没有使用适当的PK。

1 个答案:

答案 0 :(得分:1)

嗯,你快到了。只需进行一些调整,如下所示。

插入产品类型

将ID设置为自动递增,并在下面的查询中使用。

INSERT INTO `ProductsType` (type) SELECT DISTINCT `type` FROM `ProductsStored`

插入产品并通过“ ProductsType”与其类型建立联系

INSERT INTO `Products` (id, product, idType, description) SELECT ps.id, ps.product, (SELECT pt.id from ProductsType pt where pt.type=ps.type) as type, ps.description FROM ProductsStored ps

应该这样做。干杯。

相关问题