0

我有一个表,其中包含一个authors包含不同文章(不同rows)作者姓名的列。我想添加一个新列,其中包含每个作者的唯一索引,即假设列中每次出现狄更斯(只是随机选择)为 12 author

它可以通过 MySQL 查询来完成,还是我必须为此编写一个新脚本?

4

1 回答 1

0

请参阅SQL 小提琴

-- set up tables
create table Authors (
  id int(11) not null auto_increment,
  name varchar(64), 
  primary key(id)
  );

create table Books (
  id int(11) not null auto_increment,
  name varchar(64), 
  author varchar(64),
  primary key(id)
  );

-- populate Authors table, giving each author a unique ID
insert into  Authors (name)
select distinct author from Books;

-- Add an author_id column to the Books table
alter table Books add  author_id int(11) after author;

-- Update the Books table, filling in the author_ids
update Books b, Authors a
set b.author_id = a.id
where b.author = a.name;

-- If you don't care to retain the author name to author ID mapping,
-- you can then drop the Authors table.
于 2013-06-17T05:39:09.793 回答