MySql设置唯一标识,主键等设置

create table user_score(
name char(10) not null default “”,
score smallint not null default 0
);

增加一列

alter table user_score add column id smallint after name; ( 不要引号)
alter table user_score add column idea smallint;

主键&唯一键
  1. 主键不能为空 唯一键可以为空
  2. 主键only能有一个 唯一键可以有多个
  3. 主键可以多个列和并起来作为一个 唯一键不行

//在数据库表中 只有设置一个int类型的字段为主键,才可以设这个字段为标识列,标识列的作用就是一个可以自动增长的数字,如消息id,唯一并且不重复,是消息唯一标识

设置主键

alter table user_score add primary key(id);
//删除主键需要两步.
1、如果有auto_increment,先删除之; alter table user_score change id id int;
2、删除主键约束 primary key. alter table user_score drop primary key;

设置唯一约束

alter table user_score add column idea smallint auto_increment;// error一个表只能有一个自增列.
alter table user_score add column idea smallint default 0 unique; // 不好,这样往里面加数据的时候,如果不指定输入新加入的这一列,他就会被置为0,再加一个不指定的就会报错了
alter table user_score add unique(name);
//取消某一列的唯一约束
alter table user_score drop index idea;

设置某一列自增
  1. 设置它为主键 alter table user_score add primary key(id);
  2. 修改它为自增 alter table user_score change id id smallint auto_increment;
    tip: 因为自增默认值是1,所以如果此前已经有值为1的数据,那么会报错。当设置那个值为非1的值保证该列没有值为1后,设置自增才会成功,且他会把原来的都从1开始更新一遍。
    //取消自增
    alter table user_score modify column id int;
    //修改自增初始值
    alter table user_score auto_increment = 2;

MySQL 每张表只能有1个自动增长字段,这个自动增长字段即可作为主键,也可以用作非主键使用,但是请注意将自动增长字段当做非主键使用时必须必须为设置为一种“键(key)”(没有插入成功,但是自增长序列,还是会用一次增长)。主键(primary key)是键(key)的一种,key还包括外键(foreign key)、唯一键(unique key)等1. 将自动增长字段设置为主键。

  1. create table t1 (id int auto_increment Primary key,sid int);
  2. 将自动增长字段设置为非主键,注意必须显式添加Unique键。
    create table t2 (sid int primary key,id int auto_increment Unique);
  3. 将自动增长字段设置为非主键如果未添加唯一索引将会报错**,如下面语句
    create table t3 (sid int primary key,id int auto_increment)。
设置某一列的默认值
  1. 若本身已经有默认值,先删除默认值
    alter table user_score alter score drop default;
  2. 设置默值
    alter table user_score alter score set default 60;

关于change modify alter的使用

假如我们现在有一张表
《MySql设置唯一标识,主键等设置》

要改成:
《MySql设置唯一标识,主键等设置》

用一条ALTER语句实现:

ALTER TABLE hooptie RENAME TO car_table, ADD COLUMN car_id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(car_id), ADD COLUMN VIN VARCHAR(16)AFTER car_id, CHANGE COLUMN mo model VARCHAR(20), MODIFY COLUMN color AFTER model, MODIFY COLUMN year SIXTH, CHANGE COLUMN howmuch price DECIMAL(7,2);

CHANGE:如果我们不只是修改单一列,而是用一条语句改变两个列,我们需要修改列的名称,同时更改他们的数据类型,这时就需要我们用到关键字CHANGE,可以在一条语句中放入多个CHANGE,在中间加上分隔的逗号即可。

比如原来的表两列,类型为VARCHAR(50),和VARCHAR(10),现在不止要更改列名,还要更改这两列的类型。

《MySql设置唯一标识,主键等设置》

ALTER TABLE project_list CHANGE COLUMN descriptionofproj proj_desc VARCHAR(100), CHANGE COLUMN contractoronjob con_name VARCHAR(30);

MODIFY: 使用它可以只修改列的类型而不会干涉它的名称,假设要把proj_desc列的字符长度修改为VARCHAR(120)以容纳更多的说明文字,只要这么做就可以。

ALTER TABLE project_list MODIFY COLUMN proj_desc VACHAR(120);
#proj_desc是要修改的列名,VARCHAR(120)是新的数据类型

总结如下;
(1)既更改列名也更改类型,用CHANGE
(2)只修改类型,用MODIFY

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/qq_29735775/article/details/81165647
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞