目录
一、数据库的数据类型
1.整数
int 对应java中的int类型;bigint对应java中的long
int(m) 指定int类型数据的长度为m, 但是要配合zerofill使用,不足位用0代替
2.浮点数
double(m, n) m表示总长度,n表示小数点后n位(m > n),会四舍五入
decimal 高精度浮点数,设计高精度数据存储,如银行业务
3.字符串
char(n) 存储固定长度n的字符串,效率较高,在表创建过程时规定长度
varchar(n) 字符串长度不固定,但最大长度不超过n,在插入数据的时候分配具体长度;最大长度不建议超过255
text(m):可变长度字符串,存储大文本
4.时间
date:只表示年月日,默认值为null;保存数据的格式会转换为: 年-月-日
time:只表示时分秒,默认值为null
datetime:表示年月日,时分秒;默认值为null,最大数值为:9999-12-31
timestamp:表示年月日时分秒,默认值为系统当前时间;最大数值为2038-1-19,以时间戳的形式保存时间。
二、sql关键字
1.导入sql文件
sql文件以.sql为后缀,可以直接将文件中的sql语句直接导入;或者使用命令 source + 文件路径导入
1. is null 和 is not null 判断字段值是否为空
select * from 表名 where 字段名 is null | is not null
2.as 用于给显示的字段更名,可以缺省;新的名字可以是中文或者英文
3.distinct 去重,在查询字段前面添加该关键字,自动去重
select distinct dept from 表名 where 条件约束
如:select distinct deptno from emp;
4. 逻辑连接: and 和 or
5. in 和 not in 当条件设计多个字段为或的含义,可以使用in和not in减少sql语句的书写
6.模糊查询 like,后面加上占位符: _ 单个字符进行占位, % 表示可以有0个或多个字符
7.order by 将查询结果按照给定字段排序,默认升序 asc, 可以指定关键字desc,表示降序。
order by和where不连用。
select * from emp order by 字段名 (desc 该字段表示是否降序)
8. 分页查询 limit (n - 1) * m, m: n表示要查询的第几页, m为没页显示的条数
2.关于日期的函数
-
获取当前的日期(年月日时分秒)+时间 now() select now();
-
获取当前的年月日 curdate(); select curdate();
-
获取当前的时间 curtime(); select curtime();
-
从完整年月日时分秒中提取年月日 和提取时分秒 select date(now()),time(now());
-
从完整年月日时分秒中提取时间分量 extract()
-
select extract(year from now());
-
select extract(month from now());
-
select extract(day from now());
-
select extract(hour from now()); select extract(minute from now());
-
select extract(second from now());
6.日期格式化 date_format(日期,格式)
-
format:
-
%Y 四位年 %y 两位年
-
%m 两位月 %c 一位月
-
%d 日
-
%H 24小时 %h 12小时
-
%i 分
-
%s 秒
7. 把自定义时间格式转回标准格式 str_to_date(自定义的字符串时间,格式)
select str_to_date('14.08.2008 08:00:00','%d.%m.%Y %H:%i:%s');
8. ifnull(x, y) 类似三目运算符。 age = ifnull(x, y), 表示age如果为null, 则age = y;否则age = x;
3.关于字符串的函数
-
字符串拼接 concat(s1,s2) s1s2
select ename,concat(sal,'元') from emp;
2.获取字符串的长度 char_length(str) select char_length('abc');
select ename,char_length(ename) from emp;
3.获取字符串在另外一个字符串中出现的位置 注意参数位置不同用的函数不同
-格式一: instr(str,substr) select instr('abcdefg','d');
-格式二: locate(substr,str); select locate('d','abcdefg');
4.插入字符串 insert(str,start,length,newstr) length表示替代元数组的个数
select insert('abcdefg',3,2,'m');
5.转大写 转小写 select upper('nba'),lower('ABC');
6.去两端空白 trim select trim(' a b ');
7.截取字符串
- 从左边截取 select left('abcdefg',2);
- 从右边截取 select right('abcdefg',2);
8.任意位置截取 select substring('abcdefg',2); //从2截取到最后
select substring('abcdefg',2,3);//从2开始 长度为3
9.重复 repeat(str,count) select repeat('ab',2);
10.替换 replace(str,old,new) select replace('abcefg','e','mm');
11.反转 reverse(str) select reverse('abc');
4.分组查询
1.关键字:group by 字段名;
更具字段名对数据进行分组;group by语句需要放在where语句之后;通常在聚合函数的场景下使用
2. 关键字 having
与where类似,用于添加条件,having后面可以添加普通条件或者聚合函数的条件,通常应用与聚合函数条件,与group by一起使用
5.其他函数
group_concat:组连接。用于需求中要求将数据显示到一行的场景
如:查询每个人的姓名以及 学科和成绩的对应信息 每个人信息显示一行
总结
基础知识继续学习(二)
主要描述数据库中的数据类型,sql中设计的关键字及其应用(更名,去重,排序,模糊查询,分页查询)和一些常用函数(关于日期的函数,关于数学的没写,例如随机数),分组查询等;