首页 > 解决方案 > 拆分表并正确重新插入所有数据

问题描述

问题

考虑表“ProductsStored”

        |           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。另外,这种方法是正确的方法吗?

参考

如何从表中拆分数据并插入新关系?

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

标签: mysql

解决方案


嗯,你快到了。只需要一点点调整,如下所示。

插入产品类型

将 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

那应该这样做。干杯。


推荐阅读