假设我们有2个实体:
每个人都有一个地址(OneToOne关系)。因此,Address实体将具有指向其关联Person的外键(person_id)。 你会建议如何解决这个问题?
到目前为止,我只找到了一种在没有关系管理的情况下将单个实体导入mysql的方法:
LOAD DATA INFILE 'c:/tmp/file.csv'
INTO TABLE person
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
答案 0 :(得分:0)
好的,不幸的是,这将是一个艰难的答案,但可能这是没有修改你的表插入的唯一方法(这是非常不推荐)。
CREATE TEMPORARY TABLE `import` (
`person_name` varchar(300) CHARACTER SET latin1 NOT NULL,
`person_age` varchar(300) CHARACTER SET latin1 NOT NULL,
`address1` varchar(300) CHARACTER SET latin1 NOT NULL,
`city` varchar(300) CHARACTER SET latin1 NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
批量加载(正如您在问题中所示)
从导入表中执行选择,并遍历每一行
插入地址表,获取last_insert_id,然后插入带有最后一个插入ID的用户表
删除临时表:DROP TEMPORARY TABLE `import`;
如果您考虑删除自动递增ID,并转而使用UUID()
,则可以执行3次查询。
CREATE TEMPORARY TABLE `import` (
`uuid` char(36) CHARACTER SET latin1 NOT NULL,
`person_name` varchar(300) CHARACTER SET latin1 NOT NULL,
`person_age` varchar(300) CHARACTER SET latin1 NOT NULL,
`address1` varchar(300) CHARACTER SET latin1 NOT NULL,
`city` varchar(300) CHARACTER SET latin1 NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
LOAD DATA INFILE 'c:/tmp/file.csv'
INTO TABLE person
(@dummy, person_name, person_age, address1, city)
SET uuid = UUID()
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
INSERT INTO address (id, address1, city)
SELECT uuid, address1, city
FROM `import`;
INSERT INTO person (address_id, person_name, person_age)
SELECT uuid, person_name, person_age
FROM `import`;
import
;