Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 规范化-将数据迁移到另一个表_Mysql_Sql_Normalization - Fatal编程技术网

Mysql 规范化-将数据迁移到另一个表

Mysql 规范化-将数据迁移到另一个表,mysql,sql,normalization,Mysql,Sql,Normalization,我有一个带有json字段的表template。由于json对于许多template(1:n)可以相同,我创建了另一个表template\u json,并将字段template\u json\u id(FK)添加到template 为了将所有数据从一个表迁移到另一个表,我使用了以下SQL: INSERT INTO db.template_json (`json`) SELECT `json` FROM db.template; 这将完美地迁移数据,但当然会使我的template.template

我有一个带有
json
字段的表
template
。由于
json
对于许多
template
(1:n)可以相同,我创建了另一个表
template\u json
,并将字段
template\u json\u id
(FK)添加到
template

为了将所有数据从一个表迁移到另一个表,我使用了以下SQL:

INSERT INTO db.template_json (`json`)
SELECT `json`
FROM db.template;
这将完美地迁移数据,但当然会使我的
template.template\u json\u id
为空。我需要从insert中用
template\u json.id
更新每行的
template.template\u id
(FK)


是否可以在一个查询中执行此操作?

如果没有重复项,则可以使用内部联接进行更新

update template
inner join template on template_json.json = template.json
set template.template_json_id = template_json.id;
如果有重复项,则应使用select distinct填充

INSERT INTO db.template_json (`json`)
SELECT distinct `json`
FROM db.template;

如果没有复制,则可以使用内部联接进行更新

update template
inner join template on template_json.json = template.json
set template.template_json_id = template_json.id;
如果有重复项,则应使用select distinct填充

INSERT INTO db.template_json (`json`)
SELECT distinct `json`
FROM db.template;

好的,这将是一个多步骤的过程。您已经创建了新表并填充了它。下一步是消除重复项。有很多不同的方法可以做到这一点,我想到的一个方法是:

DELETE FROM template_json WHERE id in (SELECT * FROM (SELECT id FROM template_json GROUP BY json HAVING COUNT(*) > 1) as A);
这可能非常缓慢。下一步是更新现有表

UPDATE template
INNER JOIN template_json on template_json.json = template.json
SET template.template_json_id = template_json.id;
这也可能相当缓慢。json列上的索引可能会有所帮助。最后,在进行备份之后

ALTER TABLE template DROP COLUMN json;

好的,这将是一个多步骤的过程。您已经创建了新表并填充了它。下一步是消除重复项。有很多不同的方法可以做到这一点,我想到的一个方法是:

DELETE FROM template_json WHERE id in (SELECT * FROM (SELECT id FROM template_json GROUP BY json HAVING COUNT(*) > 1) as A);
这可能非常缓慢。下一步是更新现有表

UPDATE template
INNER JOIN template_json on template_json.json = template.json
SET template.template_json_id = template_json.id;
这也可能相当缓慢。json列上的索引可能会有所帮助。最后,在进行备份之后

ALTER TABLE template DROP COLUMN json;

您是否有重复项?很多json都是重复项,是的,您是否向template_json表中添加了自动递增主键?是的,
id
int(11)非空自动递增是否有重复项?很多json都是重复项,是的,您是否向template_json表中添加了自动递增主键?是的,
id
int(11)NOTNULL AUTO_Increments这可能会对迁移起作用。json实际上有重复项。这可能会在迁移中实现。json实际上有重复项。