MySQL新手入门常用的基本操作命令

一、MySQL常见操作命令

1、命令行启动与退出MySQL服务

启动:
    mysql -u用户名 -p密码
    mysql -uroot -proot
退出:
    exit/quit/Ctrl + d

2、查看MySQL版本与当前时间

查看版本:
    select version();
查看当前时间:
    select now();

二、数据库的操作命令

3、查询所有数据库

show databases;

4、新建数据库

-- create database 数据库名 charset=编码格式;
例:create database A charset = utf8;

5、查看数据库创建过程

-- show create database 数据库名;
例:show create database A;

6、使用数据库

-- use 数据库名;
例:use A;

7、删除数据库

-- drop database 数据库名;
例:drop database A;

三、表结构的操作

8、查看当前数据库中所有的表

show tables;

9、查看表结构

desc 表名;

10、创建表结构

CREATE TABLE 表名(
  字段名称 数据类型  可选的约束条件,
  字段1 字段类型[约束],
  字段2 字段类型[约束],
  字段3 字段类型[约束],
  .....
);
​
例:创建班级表
create table classes(
    id int unsigned auto_increment primary key not null,
    name varchar(10)
);
​
例:创建学生表
create table students(
    id int unsigned primary key auto_increment not null,
    name varchar(20) default '',
    age tinyint unsigned default 0,
    height decimal(5,2),
    gender enum('男','女','人妖','保密'),
    cls_id int unsigned default 0
);
​

11、修改表-添加字段

alter table 表名 add 列名 类型;
例:
alter table students add birthday datetime;

12、修改表-修改字段:重命名版

在表中已有字段 但是字段名不满足要求 类型或约束满足或者不满足均可。

alter table 表名 change 原名 新名 类型及约束;
例:
alter table students change birthday birth datetime not null;

13、修改表-修改字段:不重命名版

在表中已有字段 并且字段名也满足要求 但是类型或约束不满足要求

alter table 表名 modify 列名 类型及约束;
例:
alter table students modify birth date not null;

14、修改表-删除字段

alter table 表名 drop 列名;
例:
alter table students drop birthday;

15、删除表

drop table 表名;
例:
drop table students;

16、查看表的详细创建过程

show create table 表名;
例:
show create table classes;

四、增删改查

(一)、查询

17、查询所有列

select * from 表名;
例:
select * from classes;

18、查询指定列

select 列1,列2,... from 表名;
例:
select id,name from classes;

(二)、增加

19、全列插入:值的顺序与表结构字段的顺序完全一一对应

insert into 表名 values (...)
例:
insert into students values(0,’郭靖‘,1,'蒙古','2016-1-2');

20、部分列插入:值的顺序与给出的列顺序对应

insert into 表名 (列1,...) values(值1,...)
例:
insert into students(name,hometown,birthday) values('黄蓉','桃花岛','2016-3-2');

21、全列多行插入

insert into 表名 values(...),(...)...;
例:
insert into classes values(0,'python1'),(0,'python2');

22、部分列多少插入

insert into 表名(列1,...) values(值1,...),(值1,...)...;
例:
insert into students(name) values('杨康'),('杨过'),('小龙女');

(三)、修改

23、修改表中数据

update 表名 set 列1=值1,列2=值2... where 条件
例:
update students set gender=0,hometown='北京' where id=5;

(四)、删除

24、删除表中数据

delete from 表名 where 条件
例:
delete from students where id=5;

25、逻辑删除

其实删除文件进入回收站的本质只是在操作系统的帮助下对文件加上了 某个标记,资源管理器中对含有这种标记的文件不会显示。当从回收站恢复的时候只是移除了加上的标记而已。

-- 逻辑删除,本质就是修改操作
update students set isdelete=1 where id=1;

五、总结

1、查询句式 :select 字段名称 [as 别名] from 表;

2、更新句式: update 表名 set 字段名=新值 where 条件;

3、插入句式: insert into 表名 [全列插不填字段名] values ()[,(),()] ;

4、删除句式: delete from 表名 where 条件;

5、MySQL的常用类型:bit、int、decimal、varchar、enum、datetime等。

6、MySQL的常用约束:主键primary key、非空not null、默认default、唯一unique、自增长auto_increment、外键foreign key等。

猜你喜欢

转载自blog.csdn.net/OracleOracolo/article/details/83050471