mysql查询 - 如何拆分表数据

时间:2013-08-27 19:18:20

标签: mysql stored-procedures triggers

提前致谢。

我有一张叫做person_details的桌子。这是person_details表的示例数据。

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

我有两个名为person_dept和person_location的新表。我需要以下列方式在person_dept和person_location表中使用person_details表数据。

person_dept

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表

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

不确定我是否可以使用查询或存储过程或触发器来实现此目的。如果有人可以帮忙,我真的很感激。再次谢谢。

1 个答案:

答案 0 :(得分:0)

您正在寻找SUBSTRING_INDEX功能。如果你想在你的问题中对你的表进行strutcured,你可以使用两个INSERT查询,而不是触发器:

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;

请参阅小提琴here。如果您需要将记录自动导入person_dept和person_location表,则需要一个触发器,您可以从这样的事情开始:

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 ;