1. 基礎的查詢操作 #簡單查詢 select * from emp; //查詢emp中所有的記錄 select empno, job,ename from emp; //查詢emp表中的某些字段 select ename as 名字 from emp; //使用字段別名 去重 distinct
select distinct deotno from emp; //去除重復的行(針對字段而言) 排序 order by
#默認是升序(asc),降序(desc) select * from emp order by sal desc; //以工資按降序排序 select * from epm order by sal , deptno //多字段排序 select sal*12 annsal from epm order by annsal //別名排序 條件查詢 where
select * from emp where sal>1000; //工資大于1000的 select * from emp where sal>1000 and sal<2000; select * from emp where sal>5000 or sal<1000 select * from emp where sal<>2500 //工資不等于2500 select * from emp where sal is null //工資不空的 select * from emp where sal>0 or 1=1; //恒等式 ps:運算符的優先級:算術>連接>比較>邏輯
分組查詢(group by) 描述:將表中的數據分成若干個小組 語法:select 字段 from where 條件 group by 字段 order by 字段
#例: select 字段 from where 條件 group by 字段 order by 字段 ps:在group by 分組,select 子句,不能寫group by沒有的字段。除非這些字段用在聚合函數中 過濾 having 描述:過濾分組之后的結果,只能出現在group by 的后面
#例: select deptno , count(1),avg(sal) from emp group by deptno having avg(sal) >2000 select avg(sal) avg_sal,deptno from emp group by deptno having avg_sal>2000; 執行過程:from –where –group by --- having –select ---order by 分頁
#例: select * from emp where sal>2000 union select * from emp where deptno>20 select * from emp where sal>2000 union all select * from emp where deptno>20 使用要求:聯合的結果集必須一致(兩張表一致,查詢的字段也一致),不然會發生錯誤。