let say we have 2 entities:
Each Person has one Address (OneToOne relationship). So Address entity will have a foreign key (person_id) pointing to its associated Person. What will you suggest howto go about this?
Until now I have only found a way to import single entities into mysql without relationship management:
LOAD DATA INFILE 'c:/tmp/file.csv'
INTO TABLE person
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
OK, unfortunately this is going to be a tough answer, but likely it's the only way without modifying your table for an insert (Which is highly not recommended).
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;
Do bulk load (As you showed in your question)
Do a select from your import table, and loop through each row
Insert into address table, get last_insert_id, and then insert into user table with the last insert id
Drop your temp table with: DROP TEMPORARY TABLE `import`;
If you consider dropping the auto incrementing id, and move toward a UUID()
instead, you can do this with 3 queries.
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
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.