SQL 增删改 索引 唯一索引 主键


创建索引  

普通索引 index|key     唯一索引  unique      主键   primary key

1. alter table 库.表  add { index| unique } 索引名(某一个列名) //  ps:有名字的 索引    给某一列添加有名索引

例如:  alter table lx18.lyon add index idx_name (userName); // 向lx18 的 表lyon 中 的 userName 添加索引

例如:  alter table lx18.lyon add unique idx_name (userName); // 向lx18 的 表lyon 中 的 userName 添加w唯一索引  

2 alter table 库.表  add index (某一个列名)  //  ps:给某一列添加索引  字段名  即是 索引名

例如: alter table lx18.lyon add index (userName);

3. 创建表的时候直接加索引

create table lyon01( 

id int not null auot_increment,

userName char(20) not null,

phone int not null,

primary key(id),

unique(phone),

index(userName)

)

如下图:

alter table 库.表 下的语句 删除 索引 

1)选用DROP PRIMARY KEY子句用于删除表中的主键,由于一个表中只有

一个主键,其也是一个索引;

2)选用DROP INDEX子句用于删除各种类型的索引(普通索引 和  唯一索引);

3)选用DROP FOREIGN KEY子句用于删除外键。

例如:alter table lyon drop index userName;

例如:alter table lyon drop index age;  // 删除 index 和 unique 都是这样写

4)drop index 语句删除索引

drop index  索引名 on 库.表

例如: drop index idx_name on lx18.lyon;

创建组合索引

create index idx_name on  库.表(字段1,字段2) //  根据字段1 字段2 创建组合  idx_name (ps:索引名)

例如: create index idx_name on lx18.lyon01(userName,phone);

在已有数据库mysql_test上新建一个包含产品卖家id号、姓名、地址、

联系方式、售卖产品类型、当月销量等内容的产品卖家信息表seller,

要求在创建表的同时,为该表添加由卖家id号和售卖产品类型组成的

联合主键,并在当月销量上创建索引。\

mysql>USE mysql_test;

    Database changed

    mysql>CREATE TABLE seller

            ->(

            ->  seller_id int NOT NULL,

            ->  seller_name char(50)NOT NULL,

            ->  seller_address char(50)NULL,

            ->  seller_contact char(50)NULL,

            ->  product_type int(5)NULL,

            ->  sales int NULL,

            ->  PRIMARY KEY(seller_id,product_type),

            ->  INDEX index_seller(sales)

            ->);

    Query OK,0 rows affected(0.14 sec)

你可能感兴趣的:(SQL 增删改 索引 唯一索引 主键)