考虑表“存储的产品”

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

最佳答案

好吧,你快到了。只需如下进行一些调整。

插入产品类型

将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


那应该做。干杯。

关于mysql - 拆分表并正确重新插入所有数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56890565/

10-14 14:55
查看更多