Mysql常用命令大全

2020-05-02  本文已影响0人  囧囧的猪

创建数据库

create database database_name default charset=utf8;

删除数据库

drop database database_name;

查看数据库

show databases;

创建数据表

​ 例:创建/删除一个文章表(article)

#创建数据表基本语法
create table table_name (column_name column_type) engine=InnoDB default charset=utf8;

#创建article表
create table if not exists `article` (
  `id` bigint unsigned auto_increment comment '自增ID',
  `articleid` varchar(20) not null default '' comment '文章ID', #如果需要唯一约束添加上unique
  `category` smallint not null default 0 comment '所属类别 0:其它,1:xx, 2:xx',
  `isUp` smallint not null default 0 comment '是否置顶 0:否 1:是',
  `author` varchar(50) not null default 'undifne' comment '文章作者',
  `newest_time` datetime not null default current_timestamp comment '最新回复时间',
  `create_at` datetime not null default current_timestamp comment '创建时间',
  `update_at` datetime not null default current_timestamp on update current_timestamp comment '更新时间 自动更新',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

#删除数据表基本语法
drop table table_name;

查看表信息

#查看表结构
desc table_name;

#查看表创建信息
show table status like "table_name";

#详细查看表各字段详细信息
show full columns from table_name;

插入数据

#单条插入数据 基本语法
INSERT INTO table_name (field1, field2, ...fieldN) VALUES (value1, value2, ...valueN);
#示例:
insert into article (articleid, author) values ("dNDfdfdkNJkkDFAF", "二货");

#插入多条数据 基本语法
INSERT INTO table_name  (field1, field2,...fieldN)  VALUES  (valueA1,valueA2,...valueAN),(valueB1,valueB2,...valueBN),(valueC1,valueC2,...valueCN)......;

更新数据

UPDATE table_name SET field1=new_value1, field2=new_value2 [WHERE Clause]
#可以更新一条或多条数据
#根据where条件更新数据(基本更新数据都会有where条件)
#例:
update article set author = "二哈" where articleid = "dNDfdfdkNJkkDFAF";

#将指定字段的特殊字符串批量更新
update table_name set field=replace(field, "old_string", "new_string") [where Clause];

删除数据

DELETE FROM table_name [WHERE Clause];
#如果不加where条件,将清空数据表,不推荐!如果表数据过大容易造成阻塞卡死

ALTER

#添加
alter table table_name add field_name field_type; #添加字段并有类型限制
alter table table_name add field_name field_type first; #添加字段并放在第一位
alter table table_name add field_name field_type after field_name01; #添加字段并放在column_name01后面

#删除
alter table table_name drop field_name;

#修改
#关键字:modify, change, rename, alter [field] set default [num]
#modify: 修改字段类型设置,不可以更改字段名
#change: 修改字段类型设置 可以更改字段名
alter table table_name add unique(field_name); #添加唯一约束
alter table table_name modify field01 int(10) not null; #将字段field01类型改为int且非空
alter table table_name change field01 field02 int(10); #将字段field01更名为field02类型为int
alter table tb_test1 rename tb_test2; #将表名tb_test1更名为tb_test2
alter table table_name field_name set default 10; #设置字段默认值
alter table table_name field_name drop default; #删除字段默认值
alter table table_name engine=MYISAM; #更改表引擎类型
上一篇 下一篇

猜你喜欢

热点阅读