MySQL基础语句

A 建数据库

create database test1

B 表

  1. 建表
    create table student
    (S_id int ,
    S_name varchar(8)
    )engine myisam charset utf8;
  2. 重命名表
    rename table student to newstudent;
  3. 删除表
    drop table student;
  4. 插入数据
    insert into student
    (S_name,gender,salary)
    values
    ('Wang Yi','',4342),
    ('Li Yu','',4344);
  5. 清空表数据
    truncate student
    #truncate相当于删表后再重建一个相同结构的表
    #delete是在字段的层面上操作
  6. 修改数据
    update  student
    set 
    company='sohu'
    where
    S_id=2                                   #修改where 后面表达式为真的字段
  7. 删除数据
    #指删除整行,而不是某行中的某列
    delete from class
    where salary >8000

C MySQL的3大数据类型

  1. 数值型
    • 整型

      # Tinyint            1个字节         -128~127(0-2^7~2^7-1) 或 0~255 (共2^8个数)
      # Smallint           2个字节         -2^15~2^15-1 或 0~2^16-1 (65,535)
      # Mediumint       3个字节
      # Int                 4个字节          -2^31~2^32-1 或 0~2^32-1 (0~4,294,967,295)
      # bigint             8个字节

    • 浮点与定点

      #Float(M,D)       M<=24(为4个字节),否则为8个字节 能存储10^38,小数位10^-38              #M表示精度(总位数),D表示标度(小数位)
      #decimal(M,D)     将小数位与整数位分开存储

      create table class
      (id int zerofill not null default 0,      #zerofill 意为前排用0填充
      age Tinyint unsigned default 0,           #unsigned 意为不带正负号
      salary decimal(8,2)
  2. 字符型

    # char          #定长字符串    如果不够长度,用空格在末尾补齐 #查找快,但是浪费空间
    # varchar     #变长             不用空格补齐,但是列内容前有1~2个字节来标识列位置
    # text
    # blob         #一般存储图像,音频等二进制信息(可以防止因字符集的问题导致数据丢失)

    create table class3
    (S_name char(4) not null default '',                  #PS. varchar(M)中的M表示字符数,并非字节数,因为不同字符集的字符所占字节数不同
    S_newname varchar(4) not null default '',
    img blob                                              #声明 blob text不用给默认值
    )engine myisam charset utf8
  3. 时间类型

    #date             3个字节         范围1000-01-01到9999-12-31
    #datetime       8个字节         
    #timestamp    4个字节
    #time             3个字节         范围-838:59:59到838:59:59
    #year             1个字节         范围1901到2155以及0000

    create table test_date
    (datetime datetime not null default '0000-00-00 00:00:00',
    timestamp timestamp default current_timestamp,                      #current_timestamp为取当前时间
    time time not null default '00:00:00'
    )engine myisam charset utf8;                   

D 修改表结构

  1. 增加列
    alter table student
    add score int not null default 0   #此时增加的列位于表后
    
    alter table student
    add score int not null default 0 after S_id  #增加的列位于指定的列后
    
    alter table student
    add score int not null default 0 first #增加的列位于表头 
  2. 删除列
    alter table student
    drop score
  3. 修改列类型
    alter table student
    motify score Tinyint unsigned not null default 0
  4. 修改列名及列类型
    alter table student
    change score fenshu int not null default 0

相信自己