#簡單查詢 select * from emp; //查詢emp中全部的記錄 select empno, job,ename from emp; //查詢emp表中的某些字段 select ename as 名字 from emp; //使用字段別名
去重 distinctsql
select distinct deotno from emp; //去除重複的行(針對字段而言)
排序 order by ide
#默認是升序(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:運算符的優先級:算術>鏈接>比較>邏輯code
分組查詢(group by)
描述:將表中的數據分紅若干個小組
語法:select 字段 from where 條件 group by 字段 order by 字段blog
#例: 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
分頁it
#例: select * from emp limit 0 , 5 ; //從第1行開始取,取5行
模糊查詢io
例: select * from emp where ename like 's%' ps: %:表示0~多個任意字符 _:表示1個任意字符
#語法: select table1.column,table2.column from table1,table2 where table1.column= table2.column select dept.DEPTNO,ename ,dname from emp inner join dept on emp.DEPTNO =dept.DEPTNO select emp.ename,dept.dname from emp inner join dept using(deptno)
注意:通常的若是兩張表示經過外鍵鏈接的,使用第1,2種查詢方法,若是不是外鍵鏈接的使用1種查詢方法。第3中方式的using中填入,兩張表中字段名稱相同的字段,並且通用列字段只出現一次(即去除重複的字段)
內鏈接的特色:table
左外鏈接
描述:兩個表在鏈接的過程當中除了返回知足條件的行之外,還返回左表中不知足條件的行,這種鏈接叫左外鏈接。class
#例: select deptno ,dname,empno,ename from dept left join emp using(deptno) //左外鏈接
右外鏈接
描述:兩個表在鏈接的過程當中除了返回知足條件的行之外,還返回右表中不知足條件的行,這種鏈接叫右外鏈接。
#例: select deptno ,dname,empno,ename from dept right join emp using(deptno) //右外鏈接
全外鏈接
描述:兩個表在鏈接的過程當中除了返回知足條件的行之外,還返回兩個表中不知足條件的行,這種鏈接叫作全外鏈接。(笛卡爾積)
#例: select deptno ,dname,empno,ename from dept full join emp using(deptno) //全外鏈接
天然鏈接
描述:特殊的等值鏈接:不須要聲明相等的字段,會自動匹配
#例: select * from emp natural join dept; (等值鏈接)
外鏈接的特色
語法:select 字段 from table where 表達式 operator (子查詢字段)。
特色:子查詢在主查詢前執行一次,主查詢使用子查詢的結果
使用:
- 單行子查詢:若是使用子查詢的結果是1行,可使用比較運算符(> < <>)
- 多行子查詢:若是使用子查詢的結果是多行,則 all 、any in
- exists:select from dept e where exists (select from emp e1 where sal>2000 and e1.deptno=e.deptno)
in和exists的區別:
- in:先執行子查詢,將結果返回給主查詢,主查詢繼續執行
- 先執行主查詢,將主查詢的值依次在子查詢進行匹配,根據是否匹配返回true或者false,若是是true鏈接展現,不然不展現。
子查詢和關聯查詢的使用時機
- 子查詢:查詢條件和結果放在同一張表中
- 關聯查詢,查詢條件和結果分佈在多張表中
關鍵字:union、union all。
區別:
- union:會發生去重
- union all:不會發生去重
用法:
#例: 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
使用要求:聯合的結果集必須一致(兩張表一致,查詢的字段也一致),否則會發生錯誤。
關於sql的交集、差集、並集: