从一个表创建多个表

时间:2014-02-18 18:24:52

标签: mysql sql

我在MYsql中有一个表填充了所有数据(表:存档) 我想创建多个名为“Names”列的值的表,其中包含每个名称的alla数据

Ex. 
Table: Archive
column1     Names             column3   column4
1       John Smith          10/01/2014  35
2       John Smith          20/01/2014  36
1      Pinco Pallino        07/01/2014  30
1       Cippa Lippa         01/01/2014  20
2       Cippa Lippa         02/01/2014  21
3       Cippa Lippa         03/01/2014  19

Table: John Smith
column1 Names            column3    column4
1       John Smith          10/01/2014  35
2       John Smith          20/01/2014  36

Table: Pinco Pallino
column1 Names            column3    column4
1      Pinco Pallino        07/01/2014  30

Table: Cippa Lippa
column1 Names            column3    column4
1       Cippa Lippa         01/01/2014  20
2       Cippa Lippa         02/01/2014  21
3       Cippa Lippa         03/01/2014  19

对于“名称”中的每种名称,我必须构建一个以“名称”的值命名的表(与表:Archive相关) 我需要多个表来限制多个用户访问一个名为

的表

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用视图实现相同的访问限制,而不是破坏您的数据库结构:

CREATE VIEW cippa AS SELECT * FROM Archive WHERE Names = 'Cippa Lippa';

答案 1 :(得分:0)

如果存储过程是可接受的,这是使用存储过程完成的方法:

DELIMITER $$

CREATE PROCEDURE `split_archive`()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE name VARCHAR(255);
    --A cursor to iterate distinct names
    DECLARE curNames CURSOR FOR SELECT Names FROM Archive GROUP BY Names;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    --Preparing a statement to create a table with parametric name and select condition
    PREPARE stmtCreateTable FROM 'CREATE TABLE `?` AS SELECT * FROM Archive WHERE Names = "?"';

    --Iterating and fetching each name
    OPEN curNames;
    read_loop: LOOP
        FETCH curNames INTO name;
        IF done THEN
            LEAVE read_loop;
        END IF;

        --Since prepared statements only accept user variables
        SET @n = name;
        --Creating a table for the fetched name and populating it by executing the statement
        EXECUTE stmtCreateTable USING @n, @n;
    END LOOP;

    DEALLOCATE PREPARE stmtCreateTable;
    CLOSE curNames;
END
$$