索引SQL中列的不同值

时间:2013-06-17 05:14:35

标签: mysql sql mysqli

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

可以通过mySQL查询完成,还是我必须编写一个新脚本来执行此操作?

1 个答案:

答案 0 :(得分:0)

请参阅SQL Fiddle

-- 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.