一.查询语句以及主要作用
1.投影:根据条件选出响应的列
select sex from table;
2.选择
select * from table where name='amy';
3.连接
select t1.name,t1.sex,t1.age,t1.salary,t2.job from table1 t1,table2 t2 where t1.name=t2.name;
二.查询语句的限制和排序
1.限制
比较运算
1.>,=,<,>=,<=:
select * from table where age>20;
2.between …and…:在…和…之间(闭区间)
select *from table where age between 20 and 30;
3.in (set):匹配任意一个值
select * from table where age set(20,30);
4.like:模糊匹配
select*from table where age like `%2';
5.is null:是一个null 值
2.逻辑运算
1.and
select*from table where age=20 and sex="woman";
2.or
select*from table where age=20 or sex="woman";
3.not in
select*from table where age not in (20,30);
3.排序
order by
select*from table where age=20 order by;
三.单行函数
1.大小写转换
lower(‘SQL’)–>sql
upper(‘sql’)–>SQL
intcap(SQL learn)–>Sql Learn
2.字符函数
连接字符
concat(‘sql’,‘learn’)–>sqllearn
取子串
substr(‘sqllearn’,1,3)–>sql
取字符的长度
length(‘sqllearn’)–>8
返回子串在字符中的位置
instr(‘sqllearn’,‘q’)–>2
3.数字函数
round:向上取整
trunc:向下取整
select round(30.1264,2) trunc(20.1264,2) from table;
-->30.13 --->20.12
4.日期型函数
select systemb from table;
5.转换数据类型函数
select newage to_char(age) from table;
四.分组函数(针对多行数据操作)
1.avg:返回平均值
select avg(age) from table;
2.count:计数
select count(age) from table;
3.min,max:最小值,最大值
select min(age) from table;
4.sum:求和
select sum(age) from table;
5.group by:排序
//先分组,再求平均值
select avg(age) from table group by dept;
6.having
//先分组,再求salary大于3000的人员,having要跟在group by的后面
select dept, max(age) from table group by dept having max(salary>300);
五.多表查询
1.多表连接的种类
1.自连接:一个表自己与自己建立连接称为自连接
2.等值连接
select name,dept,age from table1,table2 where table1.dept=table2.dept;
3.外连接(左连接,右连接,全连接)
左外连接:返回左边表的列,在右表没有的,会保留为空
select name,dept,age from table1 left join table2 where table1.dept=table2.dept;
右连接:返回右边表的列,在左表没有的,会保留为空
select name,dept,age from table right join table2 where table1.dept=table2.dept;
全连接:返回右边表的列,在左表没有的,会保留为空
select name,dept,age from table1full join table2 where table1.dept=table2.dept;
六.子表查询:指嵌入到其他语句中的select语句,也可以称为嵌套查询
一个查询(子查询)是另一个查询(主查询)的输入
select name,dept,age from table where age>(select age from table2 where name='lily');