1.对数据库(DataBase)的操作
- 增加一个库
create database 库名 [charset=utf8]; - 删除一个库
drop database 库名; - 使用/进入库
use 库名; - 查看库
show databases; - 数据库的备份
#mysqldump [-P3306] -u root -P密码 -b sqltest > 文件备份路径 - 导入备份库
suorce 备份数据库的路径 - 修改库的字符集类型
alter database 库名 charset=gbk; - 查看数据库支持的字符集/校验规则
show charset;
show collation;
注:
字符集:人们将自然文字映射到计算机中表示的方法,是一些文字和字符的集合,常见的有GBK(GB2312字符集的升级版)、BIG5字符集、 GB18030字符集、UTF-8(Unicode字符集的升级版);
校对规则:(collation)是字符集中规定的一些规则(比如哪些字符规定区分大小写,哪些字符不区分大小写;
2.对数据库中表(table)的操作
2.1 增加一个表
- create table 表名(字段名 字段数据类型,……)
create table student (
学号 int, 姓名 varchar(32), 性别 char(2),
年龄 int, 年级int, 专业 varchar(50)
)character set utf8;
2.2 删除
-
删除一行:delete from 表名 where name=’ ws ';
-
删除单列:alter table 表名 drop column 列名
-
删除表中全部内容:delete from 表名;
-
删除表:drop table 表名
2.3 改
-
插入单行:insert into 表名 (字段) values (字段内容,……);
insert into Strdents (姓名,性别,出生日期)
values (‘开心朋朋’,‘男’,‘1980/6/15’);
-
插入多行:insert into 表名 (字段) values (字段内容1), (字段内容2)……;
-
重命名表: rename table 旧名 to 新名;
-
修改列名:alter table 表名 change column name newname varchar(20);
-
修改字段的数据类型:alter table 表名 modify sex varchar(2)
-
更新:update salary set salary=5000.00
2.4 查找
-
查看表结构:desc 表名;
-
查看整张表:select * from 表名;
-
按列查询:select 字段名 from 表名;
-
按行查询:select * from 表名 where 筛选条件;
-
分组查询:select * from 表名 group by 某个字段;
-
排序:select * from 表名 order by 字段名;
默认升序,规定降序在最后加desc即可; -
查询同时去掉重复的元素:
select distinct name from studentwhere sum>=200; -
合并查询
union(去重)、union all(不去重)
select ename, sal, job
from EMP where sal>2500
union
select ename, sal, job
from EMP where job='MANAGER';
--去掉了重复记录
两个数据集的交集
2.5 表的约束
-
增加主键
alter table table_name add column id int(11) primary key auto_increment;
删除主键
alter table 表名 drop primary key; -
自动增加(自增长)
alter table table_name add column id int(11) primary key auto_increment; -
非空
not null -
默认值
default ‘xx’ -
唯一值
unique -
注释
comment -
外键
foreign key (字段名) references 主表(列)
2.6 Where查询
-
等于: =
-
不等于:<>、!=
-
在…之间:between a0 and a1
-
在…里的任意一个:in(option,…)
-
空:is null
-
不为空:is not null
-
模糊匹配:like //%表示任意多个;_表示任意一个
-
and、or、not
2.7 函数
- 日期函数:
年月日:select current_date();
时分秒:select current_time();
时间戳(上面两个相加):select current_timestamp(); - 字符串函数:
连接字符串:concat();
返回2在1中的位置:instr(2,1);
转大写:ucase();
转小写:lcase();
在1中把2替换成3:replace(1,2,3);
比较字符串大小:strcmp();
去除空格:ltrim(str);
从n开始取m个:limit(n,m); - 数学函数:
绝对值:abs()
十进制转二进制:bin()
随机浮点数:rand()
取模:mod()
数量:count()
总和:sum()
平均:avg()
最大:max()
最小:min()