mysql操作

管理Mysql

  1. 列出所有数据库

Show databases;

  1. 创建一个新数据库(test)

Create database test;

  1. 删除一个数据库(test)

Drop database test;

注意:删除一个数据库将导致该数据库的所有表全部被删除

  1. 切换为当前(test)数据库

Use test;

  1. 列出当前数据库的所有表

Show tables;

  1. 查看当前表结构(students)

Desc students;

  1. 创建表的SQL语句

Show create table students;

Create table `students` (

`id` bigint(20) not null auto_increment,

`class_id` bigint(20) not null,

`name` varchar(100) not null,

`gender` varchar(1) not null,

`score` int(11) not null,

Primary key (`id`)

) engine=InnoDB auto_increment=1 default charset=utf8

  1. 删除表

Drop table students;

  1. 给students表新增一列birth

Alter table students add colimn birth varchar(10) not null;

  1. 修改birth列,例如把列名改为birthday,类型为varchar(20)

Alter table students change colimn birth birthday varchar(20) not null;

  1. 删除列

Alter table studens drop colimn birthday

  1. 退出mysql

Exit

  1. 插入一条新记录,但如果记录已经存在就线删除原记录再插入新记录。此时可以用replace语句,这样就不必先查询再决定是否先删除再插入(插入或替换)

Replace into students (id, class_id, name, gender, score) values (1,1,’小任’,’F’,100)

  1. 插入或更新。如果我们希望插入一条新记录(insert),但如果记录已经存在就更新改记录。此时可以用insert into … on duplicate key update … 语句

Insert into students (id, class_id, name, gender, score) values (1,1,’小任’,’F’,90) on duplicate key update name=’小明’, gender=”F”, score=90

  1. 插入或忽略。如果我们希望插入一条新记录(insert),但如果记录已经存在,就啥事也不干直接忽略,此时可以使用insert ignore into …

Insert ignore into students (id, class_id, name, gender, score) values (1,1,’小任’,’F’,99)

  1. 快照。如果想要对一个表进行快照。即复制一份当前表的数据到一个新表,可以结合create table和select

Create table students_of_class1 select * from students where class_id=1;

新创建的表结构和select使用的表结构完全一致

  1. 写入查询结果集

如果查询结果集需要写入到表中,可以结合insert和select,将select语句的结果集直接插入到指定集中。

例如:创建一个统计成绩的表score,记录各班的平均成绩

Create table score (

Id bigint not null auto_increment,

Class_id bigint not null,

Average double not null,

Primary key (id)

);

然后就可以用一条语句写入各班的平均成绩:

Insert into score (class_id, average) select class_id, avg(score) from group by class_id;

posted @ 2019-01-04 21:30  明烟雨任  阅读(206)  评论(0编辑  收藏  举报