数据库 SQL语句

一、基础操作

1、 数据库表的创建

create table student(

int primary key auto_increment,     
name varchar(20) unique,               
age int                                 
)   

2、表的相关约束

              primary key (非空并且唯一):能够唯一区分当前记录的字段称为主键

    unique: 唯一,就是数据不能有重复的,一旦有重复就会报错

    not null: 该列数据不能为空,否则报错

    auto_increment: 主键字段必须是数字类型

    foreign key:外键约束 (外码)

3、查看表  (仅用student为代表)

       desc student  查看表结构

  show columns from student  查看表结构

  show tables    查看当前数据的所有表

  show create table student  查看表的创建语句

4、修改表结构 

①增

               alter table student add [列名] 类型 [约束性条件] [first|after 列名]

    alter table student add abd int after name;  添加abd列,指定它在 name 列的后面

    alter table student add aba int first ;    添加ada列,指定该列在 最前面

    alter table student add abs int,        添加多列

②删 (列)

              alter table 表 drop [column] 列名

    alter table student drop aBa;

    alter table student drop column abd,drop column abs;

表:

              drop table 表名;

③改

 列的类型:

               alter table student modify 列名 类型 [约束条件] [first|after 字段名]

    alter table student modify aba varchar(20) unique; 将 aba 列修饰成 唯一 字段

列名:

              alter table 表  change 列名 新列名 类型 [约束条件] [first|after 字段名]

    alter table student change aba bcd varchar(10);  将aba 修改成 aBa    紧跟在原来的名字后面

表名:

              rename table 表名 to 新表名;

              rename student to Student;

④查

       基本结构: 

      select 

        from 

       where

二、创建索引

 索引:

  普通索引:

              alter table student add (index|key) [索引名](字段.....)

    1.alter table student add index (name)  #为name创建索引,索引名默认为字段名

    2.alter table student add index username(name)  #为name创建索引,索引名为username

    注意:key和index的使用方法一样

  唯一索引:

                  alter table studnet add unique (index|key) [索引名](字段名....)

    1.alter table studnet add unique index username(name)  #为字段name创建唯一索引,索引名为username

  

  联合索引:

    1.alter table student add index user_age(name, age)

    2.alter table student add unique index user_age(name, age)

  删除索引:

    alter table student drop (index|key) 字段名

    1.alter table student drop index username  

 今天的分享就结束啦,在针对相关的增删改查的训练和记忆的时候,还是要针对相应的习题开始,这样才有利于加深自己的理解。

猜你喜欢

转载自www.cnblogs.com/bibabo/p/9351081.html