Thanks in advance.
I have a table, called person_details. Here's the sample dat of person_details table.
ID Name_and_Dept Location ------------------------------------- 1 John Doe - Finance New York 2 Emmy Joe - IT Boston 3 Stella Job - Admin Chicago 4 Steve Doe - Finance Los Angeles 5 Frank Chad - Sales Boston 6 Rich Moss - Admin New York
I have two new tables called person_dept and person_location. I need the person_details table data in both person_dept and person_location tables in following way.
table 表
P_ID Name Dept --------------------------- 1 John Doe Finance 2 Emmy Joe IT 3 Stella Job Admin 4 Steve Doe Finance 5 Frank Chad Sales 6 Rich Moss Admin
person_location table
L_ID Name Location --------------------------- 1 John Doe New York 2 Emmy Joe Boston 3 Stella Job Chicago 4 Steve Doe Los Angeles 5 Frank Chad Boston 6 Rich Moss New York
Not sure if I can achieve this using a query or stored proc or a trigger. I really appreciate if someone could please help. Thanks, again.
You are looking for SUBSTRING_INDEX function. If you want your tables strutcured as in your question, you could use two INSERT queries like these ones instead of a trigger:
INSERT INTO person_dept
SELECT
ID,
SUBSTRING_INDEX(Name_and_Dept, ' - ', 1),
SUBSTRING_INDEX(Name_and_Dept, ' - ', -1)
FROM person_details;
INSERT INTO person_location
SELECT
ID,
SUBSTRING_INDEX(Name_and_Dept, ' - ', 1),
Location
FROM person_details;
Please see fiddle here . If you need the record to be automatically into person_dept and person_location table, you need a trigger, and you could start with something like this:
DELIMITER |
CREATE TRIGGER populate_tables AFTER
INSERT ON person_details
BEGIN
INSERT INTO person_dept VALUES
(new.ID,
SUBSTRING_INDEX(new.Name_and_Dept, ' - ', 1),
SUBSTRING_INDEX(new.Name_and_Dept, ' - ', -1)
);
INSERT INTO person_location
VALUES
(new.ID,
SUBSTRING_INDEX(new.Name_and_Dept, ' - ', 1),
new.Location
);
END;
|
DELIMITER ;
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.