mysql - 拆分表并正确重新插入所有数据
问题描述
问题
考虑表“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。
解决方案
嗯,你快到了。只需要一点点调整,如下所示。
插入产品类型
将 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
那应该这样做。干杯。
推荐阅读
- c# - 从事件查看器中读取转发的事件
- git - 批处理命令中的Git hub文件路径-Jenkins
- html - CSS中带有以下线条的自定义选项卡
- reactjs - React.createElement:类型无效,预期为字符串或类/函数,但得到:
- docusignapi - 我们可以从 Docusign 标题中隐藏菜单选项吗
- json - 无法从 Json.parse 获取值在 Angular js MVC 中获取未定义的值
- java - 如何使用 Kurento 媒体服务器高效地进行电话会议
- mysql - 如何使用 mysqljs 包为 nodejs 创建触发器?
- c# - 从数据库填充下拉列表的问题(依赖下拉列表)
- c++ - 使用函数在函数中声明数组值