全国统一服务热线

173-5346-7304

新闻中心

当前位置:首页>新闻中心

MySQL有哪些常用基础命令

本文主要跟大家总结一些常用的MySQL基础命令,以后如果有忘记的命令回过头很容易就可以找到。

1、MySQL功能型语句

show databases 查询所有数据库;

use database 切换数据库;

create database [if not exits] 库名 创建数据库;

drop database [if exits] 库名 删除数据库;

show 建库语句 查询数据库创建;

character set 设置数据库的字符集;

alter database 数据库名 character set 编码集 修改数据库的编码集;

以上的命令在执行时加分号表示结束。

2、建表语句

create table [if not exists] 表名(

字段1 数据类型 字段属性,

字段2 数据类型 字段属性,...

字段N 数据类型 字段属性

)engine=引擎 default charset=编码集;

select database(); #查看当前数据库

show create table 表名 #查看建表语句

desc 表名 #查看表结构;

drop table [if exists] 表名 #删除表

3、字段属性

not null:没有给值数据的时候为默认值,而varchar的默认值不设置的话为空;

auto_increment:定义列为自增的属性,一般是用于主键自增,数值会在上一行基础上加1;

primary key:关键字用于定义列为主键,也可以多列定义组合主键,列间以逗号分隔;

engine:设置存储引擎,charset设置编码;

default null:设置默认值null;

default 值:设置默认值。

我们在建表的时候可以根据需要选择字段设置。

create table if not EXISTS student (

id int auto_increment,

`name` VARCHAR(32),

age int,

sex char(1),

clazz VARCHAR(32)) charset utf8;

4、修改表

-- 修改表名:

alter/rename table student1 TO `student`;

-- 添加字段:

alter table student add city varchar(32) default '其他';

-- 修改字段:

alter table student MODIFY varchar(356);

5、增删改查

-- 增

insert into 表名(字段) values(值),(值)...(值);

-- 删

delete from student where city='其他';

-- 改

update student set city='杭州'where name ='李';

-- 查

SELECT id as di,name,job,score from student where score>18;

6、子句

-- > < <= >= = != 大于、小于、大于(小于)等于、不等于

SELECT * from student WHERE id>1006;

SELECT * from student WHERE id!=1006;

--between ...and... 显示在某一区间的值,左闭右闭,也可对字符串进行范围查询

select id,name,job from student where id BETWEEN 1002 and 1005;

select * from student where job BETWEEN 'a' and 'b';

-- in(set) 显示在in列表中的值,例:in(100,200)只能匹配100或200,跟between的用法类似

select * from student where job in('a','b');

-- like 使用模糊匹配

SELECT * from student where name like 'l_';

7、limit分页

-- 语句 limit 开始下标,长度;1,2表示取行后面的两行

select * from student LIMIT 1,2;

8、去重

-- 去重 DISTINCT 字段1,字段2...字段N,需要注意的是DISTINCT需要放在字段之前

select DISTINCT name from student;

select count(DISTINCT name) from student;

9、排序

-- 可以跟在查询之后对结果进行排序;默认升序asc,降序desc

SELECT * from student ORDER BY score,job;

ELECT * from student ORDER BY score desc, job desc;

10、分组

-- group by 字段1,字段2...字段n;

-- 需要注意的是分组之后每组数据默认显示条数据

SELECT count(*) as c,job,`name`,id from student GROUP BY sex HAVING c>2;

--where having 一起使用

SELECT count(*)as c,name,id FROM student where sex='男' HAVING c>3;

-- where 是对表中from到的数据进行筛选;

-- having是对表中selec显示数据进行筛选


QQ咨询
在线咨询
在线报名
173-5346-7304
173-5346-7304
返回顶部