常见Hql语句 财富值43

2天前发布

常见的 Hql 语句
1 >过滤
where 、limit、distinct、between and 、null、is not null
select * from emp where sal > 3000;
45
select * from emp limit 5; 查看五行内容
select distinct deptno from emp;
select * from emp where sal between 1000 and 3000;
select empno,ename from emp where comm is null;
select empno,ename from emp where comm is not null;
2> 聚合函数
count、max、min、avg、sum、group by、having
select avg(sal) avg_sal from emp ;
按照部门分组求出每个部门的平均工资
**select 中出现的字段,需要用聚合函数包裹或者放入 group by 中
select deptno,avg(sal) avg_sal from emp group by deptno;
deptno avg_sal
10 2916.6666666666665
20 2175.0
30 1566.6666666666667
select deptno,max(job),avg(sal) from emp group by deptno;
deptno _c1 _c2
10 PRESIDENT 2916.6666666666665
20 MANAGER 2175.0
30 SALESMAN 1566.6666666666667
having 和 where 用法都差不多,都是筛选语句
可以一起使用,先 where 后执行 having
select deptno,avg(sal) avg_sal from emp group by deptno having avg_sal > 2000 ;
3> join
left join、right join、inner join(等值)、full join(全)
创建两张表
A 表: B 表:
ID Name ID phone
1 张三 1 111
2 李四 2 222
3 王五 3 333
5 赵六 4 444
load data local inpath "/opt/datas/A.txt" into table A;
load data local inpath "/opt/datas/B.txt" into table B;
等值 join:
select a.ID,a.Name,b.ID ,b.phone from A a join B b on a.ID=b.ID;
左 join:以左表为基准,没有匹配到的字段为 Null
46
select a.ID,a.Name,b.ID ,b.phone from A a left join B b on a.ID=b.ID;
右 join:以右表为基准,没有匹配到的字段为 Null
select a.ID,a.Name,b.ID ,b.phone from A a right join B b on a.ID=b.ID;
全 join:所有的字段都会出现,匹配或者匹配不到都会出现,没有匹配上的字段就是 Null
select a.ID,a.Name,b.ID ,b.phone from A a full join B b on a.ID=b.ID;