1. 程式人生 > >having 和where的區別

having 和where的區別

在查詢過程中聚合語句(sum,min,max,avg,count)要比having子句優先執行.而where子句在查詢過程中執行優先級別優先於聚合語句(sum,min,max,avg,count)。



--having子句,對分組查詢的結果進行過濾
  --查詢部門號大於10的不同部門的不同工作崗位的人數
  select deptno,job, count(*) from emp where deptno > 10 group by deptno,job;--from -where-group by
  select deptno,job, count(*) from emp group by deptno,job having deptno >10;--from -group by-having
  --當where和having都可以使用的時候,這時優先使用where,where執行效率高
 
  --查詢不同部門的不同工作崗位的人數並且人數大於1的資訊
    --多行函式必須先分組再過濾
   select deptno,job, count(*) from emp group by deptno,job having  count(*) >1;
  
  --統計人數小於4的部門的平均工資。
   select avg(sal), count(*)
     from emp
    group by deptno         --分組
   having count(*) < 6      --過濾
    order by avg(sal) desc; --排序


  --統計各部門的最高工資,排除最高工資小於3000的部門。
   select max(sal)
     from emp
    group by deptno
   having max(sal) >= 3000
    order by max(sal) desc;



--查詢條件where子句使用算術表示式 = ,< , > ,>= ,<= ,<>
--檢視工資等於1250的員工資訊
select * from emp where sal = 1250;
--檢視工作是CLERK的員工資訊,注意大小寫
select * from emp where job = 'clerk';--查詢的值是區分大小寫
    SELECT * from emp where job = 'CLERK';--關鍵字不區分大小寫
--檢視工資大於1250的員工姓名和工作
select ename,job,sal from emp  where sal>1250 order by sal ;--order by關鍵字放到where後面
--檢視工資大於等於2000的員工資訊
select * from emp  where sal>=1250;
--檢視工資小於等於2000的員工資訊;
select * from emp  where sal<=1250;
--檢視工資不等於1500的員工資訊
select * from emp where sal <> 1250;
--檢視入職日期在1981年後的員工資訊
    select * from emp where hiredate > '31-12月-1981';-- 日期預設的格式 日月年 





--where子句使用關鍵字  and,between, or, in, like ,is null ,is not null
--查詢工資在2000-3000(包括2000和3000)之間的員工資訊
    select * from emp where sal>=2000 and sal<=3000; --and
    select * from emp where sal between 2000 and 3000;--between and
  --查詢工作為SALESMAN,ANALYST,MANAGER的員工資訊
    select * from emp where job='SALESMAN' or job='ANALYST' or  job='MANAGER'; --or
    select * from emp where job in('SALESMAN','ANALYST','MANAGER'); --in
  --查詢姓名中包含s的,以s開頭的,以s結尾的,第二個字元為A的,包含下劃線的名字。
    select * from emp where ename like '%S%';--%代表一到多個任意的字元
    select * from emp where ename like 'S%'; --S開頭
    select * from emp where ename like '%S';--S結尾
    select * from emp where ename like '_A%';--下劃線代表任意一個字元
   
    
  --查詢名字中包含下劃線的使用者資訊
     select * from emp where ename like '%A_%' escape 'A'; --escape '\'轉義字元
  --查詢有津貼獎金的員工資訊
     select * from emp where comm >0;
     select * from emp where comm is not null; --包含獎金為0的員工資訊 
     select * from emp where comm is null;  
  --修改表的資料
    select * from emp for update;