十五、利用SELECT檢索資料
阿新 • • 發佈:2018-12-02
利用SELECT檢索資料
1、DISTINCT關鍵字去重
SELECT distinct(job) from EMP t
- DISTINCT括號裡可以有一列或者多列,多列會被當成一個整體對待。
2、ORDER BY 排序
按列 c2 的升序排列
select * from tablename order by c2 asc;
按列 c2 的降序排列
select * from tablename order by c2 desc;
複合排序,先按列 c1 升序排列,再按 c2 降序排列
select * from tablename order by c1 asc, c2 desc;
3、LIKE模糊查詢
例1,查詢name欄位中包含有“明”字的。 select * from table1 where name like '%明%' 例2,查詢name欄位中以“李”字開頭。 select * from table1 where name like '李*' 例3,查詢name欄位中含有數字的。 select * from table1 where name like '%[0-9]%' 例4,查詢name欄位中含有小寫字母的。 select * from table1 where name like '%[a-z]%'
4、IN查詢條件限制在某列表
IN 列表查詢
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
NOT IN列表查詢
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
5、IS NULL空值查詢
select * from a where b is null
6、GROUP BY分組查詢
- 可以用在WHERE或者From後面。
以下查詢可以通過: select t.job from EMP t group by t.job 以下是錯誤示範: select t.job,t.ename from EMP t group by t.job
查詢出來的資訊,只能是GROUP BY只能是指定的欄位或者是分組函式。
- 分組函式:就是對一組中的資料進行處理獲取一個結果
Count:統計查詢結果有幾條記錄,如果資料庫表的沒有資料, count(*)返回的不是 null,而是 0
Select count(*) from dual;
Select avg(comm) from emp;--平均值
Select max(comm) from emp;--最大值
Select min(comm) from emp;--最小值
Select sum(comm) from emp;--總和
--分組列中空值,可使用Nvl()函式強制分組函式處理空值
select avg(nvl(comm, 0)) from emp;
7、HAVING 子句的使用
- 對group by 分組後,再進行條件限制
正確例子:
select t.job from EMP t group by t.job having t.job='CLERK'
錯誤示範:having後面只能跟著分組函式、或者group by指定的欄位
select t.job from EMP t group by t.job having t.deptno>10