简体   繁体   English

如何将列值复制到新的 SQL 表、删除重复项并创建映射?

[英]How to copy column values to a new SQL table, remove duplicates and create mappings?

I have a table Excerpt我有一张桌子Excerpt

    CREATE TABLE IF NOT EXISTS excerpt(
      excerptID INT UNSIGNED NOT NULL AUTO_INCREMENT, 
      author VARCHAR(45) NOT NULL, 
      title VARCHAR(255) NOT NULL, 
      text VARCHAR(2500) NOT NULL,
      comments VARCHAR(2500) NOT NULL,
      PRIMARY KEY (excerptID)
    ) ENGINE=INNODB CHARACTER SET utf8mb4;

摘抄

and want to remove its column Author while distributing its (often duplicate) values and information about these values into two new tables Author并希望在散发有关这些值的(通常复制)值和信息删除其列作者为两个新表Author

CREATE TABLE IF NOT EXISTS author(
  authorID INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(45) NOT NULL , 
  PRIMARY KEY (authorID)
) ENGINE=INNODB CHARACTER SET utf8mb4;

作者

and AuthorMap :AuthorMap

CREATE TABLE IF NOT EXISTS authormap (
  excerptID INT UNSIGNED NOT NULL, 
  authorID INT UNSIGNED NOT NULL, 
  PRIMARY KEY (excerptID, authorID),
    CONSTRAINT authorMapFK FOREIGN KEY (excerptID) REFERENCES excerpt (excerptID)
    ON DELETE CASCADE 
    ON UPDATE CASCADE,
    CONSTRAINT authorFK FOREIGN KEY (authorID) REFERENCES author (authorID)
    ON DELETE CASCADE 
    ON UPDATE CASCADE
) ENGINE=INNODB;

作者地图

All duplicates should be removed and mappings between excerptID and authorID placed into AuthorMap , ie eventually all unique author names should be in the table Author , their IDs created and all ExcerptID should be copied to AuthorMap alongside with the newly created AuthorIDs.应删除所有重复项并将excerptIDauthorID之间的映射放入AuthorMap ,即最终所有唯一的作者姓名都应在表Author ,创建的 ID 和所有ExcerptID应与新创建的 AuthorID 一起复制到AuthorMap

How should I do it?我该怎么做?

You can create the table authors as:您可以将表authors创建为:

create table authors (
    author_id int auto_increment primary key,
    name varchar(255)  -- or whatever
);

insert into authors (name)
    select distinct author
    from excerpt;

Then create the author map table as:然后将作者映射表创建为:

create table excerptAuthors (
    excerptAuthorsId int auto_icnrement primary key,
    excerptid int,
    authorid int
);

And finally:最后:

insert into excerptAuthors (excerptId, authorId)
    select e.excerptId, a.authorId
    from excerpts e join
         authors a
         on e.author = a.name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM