简体   繁体   中英

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

I have a table 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

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 :

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.

How should I do it?

You can create the table authors as:

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;

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.

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