MySQL(2)数据库和数据表管理

数据库管理

  • 查看当前所有的数据库: show databases;

  • 创建数据库:create database 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

    create database day25db;
    
    create database day25db DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
    
  • 删除数据库:drop database 数据库名;

  • 进入数据(进入文件):use 数据库;

数据表管理

  • 进入数据库 use 数据库;,查看当前所有表:show tables;

  • 创建表结构

    create table 表名(
        列名  类型,
        列名  类型,
        列名  类型
    )default charset=utf8;
    
    create table tb4(
    	id int primary key,			 -- 主键(不允许为空、不能重复)
        name varchar(16) not null,   -- 不允许为空
        email varchar(32) null,      -- 允许为空(默认)
        age int default 3            -- 插入数据时,如果不给age列设置值,默认值:3
    )default charset=utf8;
    

    主键一般用于表示当前这条数据的ID编号(类似于人的身份证),需要我们自己来维护一个不重复的值,比较繁琐。所以,在数据库中一般会将主键和自增结合。

    create table tb5(
    	id int not null auto_increment primary key,	-- 不允许为空 & 主键 & 自增
        name varchar(16) not null,   		-- 不允许为空
        email varchar(32) null,      		-- 允许为空(默认)
        age int default 3            		-- 插入数据时,如果不给age列设置值,默认值:3
    )default charset=utf8;
    

    注意:一个表中只能有一个自增列【自增列,一般都是主键】。

  • 删除表 drop table 表名;

  • 清空表 delete from 表名;truncate table 表名;(速度快、无法回滚撤销等)

  • 修改表

    • 添加列

      alter table 表名 add 列名 类型;
      alter table 表名 add 列名 类型 DEFAULT 默认值;
      alter table 表名 add 列名 类型 not null default 默认值;
      alter table 表名 add 列名 类型 not null primary key auto_increment;
      
    • 删除列

      alter table 表名 drop column 列名;
      
  • 修改列 类型

    alter table 表名 modify column 列名 类型;
    
  • 修改列 类型 + 名称

    alter table 表名 change 原列名 新列名 新类型;
    
    alter table  tb change id nid int not null;
    alter table  tb change id id int not null default 5;
    alter table  tb change id id int not null primary key auto_increment;
    
    alter table  tb change id id int; -- 允许为空,删除默认值,删除自增。
    
  • 修改列 默认值

    ALTER TABLE 表名 ALTER 列名 SET DEFAULT 1000;
    
  • 删除列 默认值

    ALTER TABLE 表名 ALTER 列名 DROP DEFAULT;
    
  • 添加主键

    alter table 表名 add primary key(列名);
    
  • 删除主键

    alter table 表名 drop primary key;
    
  • 常见列类型

    • int
    • float
    • double
    • enum
    • set
    • time
    • char
    • varchar
    • text
    • datetime
  • 查看表结构

    describe t1; #查看表结构,可简写为desc 表名
    
    show create table t1\G; #查看表详细结构,可加\G
    
posted @ 2021-11-12 23:06  下个ID见  阅读(83)  评论(0)    收藏  举报