1.导入文件至数据库
source 加文件路径
2.selece
select 字段名 from 表名
3.distinct查询不重复记录
select distinct 字段 from 表名
4.where 有条件查询
select '字段' from 表名 where 条件
5.and;or
select 字段名 from 表名 where 条件1 and/or 条件2 and/or 条件3
6.显示已知值的资料
select 字段名 from 表名 where 字段 in ('值1' '值2'..);
7.between 显示两个值范围内的资料
select 字段名 from 表名 where 字段 between '值1' and '值2';
8.like 通配符
selewct 字段名 from 表名 where 字段 like '模式'
9.order by 按关键字排序
select 字段名 from 表名 where 条件 order by 字段 [asc正向排序/desc反向排序] 默认为正向排序,可不写
10.数学函数
select abs(-x) ;
返回绝对值
|-x|select randd(x);
随机生成x个数
select 字段名 from 表名 order by rand()
随机生成排序
select mod(x,y)
返回x除以y后的余数
select power(x,y);
返回x的y次方
select round(带小数点的数)
返回离该数字最近的整数
select round(x,y);
返回x的y位四舍五入后的值
select truncate(x,y);
返回数字x阶段为y位小数的值
select ceil(2);
返回大于等于x的最小整数
select greatest(a,b,c,d,e,f) ;
返回集合中最大的值
select least(a,b,c,d,e,f);
返回集合中最小的值
聚合函数
select avg(age) from 表名 ;
求表中age的平均值
select sum(age) from 表名 ;
求表中的年龄的总和
select min(age) from 表名;
求表中年龄最小的值
select count(字段) from 表名;
求表中有多少该字段非空记录count(明确字段):不会忽略空记录
select count(*) from 表名 ;
求表中有多少条记录会忽略空字段
insert into 表名 values(x,y,z,' ');
插入,空格也能识别
字符串函数
- select trim (位置 要移除的字符串 from 字符串); 其中位置的值可以是:leading(开始)、trailing(结尾)、both(起头及结尾)#区分大小写
- select length (字段) from 表名;
计算出字段中长度的字符长度
select name,length(name) from students;
select replace(字段.'原字符''替换字符')from 表名:
替换表中出现相同字符(字符串中的部分相同字符也会查找到并且替换掉)
select concat(字段1,(可加制表符),字段2)from 表名 where 字段n=x;
将两个字段拼在一起
select substr(字段,开始截取字符,截取的长度) where 字段='截取的字符串';
截取字符串
select 字段1,sum(字段2) from 表名 group by 字段1;
对group by后面的字段的查询结果进行汇总 分组,通常是结合聚合函数一起使用的、group by有一个原则,就是select后面的所有列中,没有使用聚合函数的列必须出现在group by的后面。
select 字段1,sum('字段2')from 表格名 by字段1 having (函数条件);
having是用来过滤有group by语句返回的记录集,通常与group by语句联合使用(hanving语句弥补了where关键字不能与聚合函数联合使用的不足,如果被select的只有函数栏,那就不需要group by子句)
select "表格别名"."栏位1"[as]"栏位别名"from"表格名"[as]"表格别名";
连接查询
1.inner join(等值相连)
只返回两个表中联结字段相等的行
select *from student A inner join scores B on A.stuid=B.stuid;
2.left join(左联接)返回包括左表中的所有记录和右表中联结字段相等的记录
3.right join(右联接)返回包括右表中的所有记录和左表中联结字段相等的记录
子查询
连接表格,在where 子句或having子句中插入另一个SQL语句
语法:select "栏位1" from "表格1" where "栏位2"[比较运算符];
外查询: select "栏位1" from "表格1" where "条件";
select sun(score) from scores where stuid in (select stuid from sstudents where stuid=1);
exists
- 用来测试內查询有没有产生任何结果类似boolean值是否为真。
- 如果有的话,系统就回执行外查询中的SQL语句。若是没有的话,那整个SQL语句就不会产生任何结果。
语法:select "栏位1" from "表格1" where exists(select * from "表格2" where "条件");
事例:先看students表中是否有stuid为1的学生,如果有则执行将scores表中的scores求和
select sum(score) from scores where exists (select * from students where stuid=1);