sql 教程系列 一、檢索資料

來源:互聯網
上載者:User

在開始本教程之前,需要準備兩張表 ,這個在oracle中是有的 大家都知道的emp 和dept表

emp (empno,ename,job,mgr,hirdate,sal,comm,depetno)dept(deptno,dname,loc)

sql語句大部分適合myql

1從表中檢索資料

select * from emp (*代表所有的列都要返回)

2從表檢索出部分列

select empno,ename from emp(指定列的名字,逗號相隔就可以了)

3尋找滿足條件的列

select  * from emp where empmo= 12300(可以在where後面加限制的條件)select * from emp where empno = 67777 and depto=10 (滿足多個條件用and聯結就可以了 是且的意思)select * from emp where empno =898989 or deptno = 11(滿足員工號為898989 或者部門為10的員工的結果)

3為列取別名

select sal as salary ,comm as commission  from emp ( as 加別名 as 可以省略)

4在where中使用別名

select sal as salary from emp where salary >10000 是錯的

sql執行的順序是先進行from 然後進行where進行過濾 ,最後執行select 所以在執行where 的時候還沒有執行select 也就不知道別名到底是哪列了

解決的方法有就是使用內聯視圖

select * from (       select sal as salary from emp  ) x where x.salary>10000

可見這樣的效率極低啊  

5在select中使用邏輯條件陳述式

有這麼一個需求 ,查詢一個員工表 ,如果工資大於1000就顯示high,小於500就顯示lower,如果在兩者之間就顯示ok

select ename , sal,  case when sal<500 then 'lower'##case when then就是相當於java中的if else          when sal >1000 then 'high'          else 'ok'  end as status#給列取別名 from emp

6分頁

select * from emp limit 0,5#返回前五條select *from emp limit 2,5#從第二條開始擷取他後面的五條記錄

7對空值的限制

select  * from emp where com =null #錯誤select * from emp where comm is null#正確 取反的用 is not null

8查詢到空值的時候將其轉換為實際想要的值

例如你在查詢獎金的時候要是查詢到null,你想到得到是0,那麼怎麼辦呢?

select coalesce(comm,0) from emp #意思是說如果comm為null 就返回0 不為null 就返回其本身

還可以用邏輯判斷

select case                when comm is null then 0                else comm             end as commissionfrom emp

9 in語句

如果你要查詢部門為10 和20的員工資訊

select * from emp where deptno in(10,20) # 取反 就是not in這樣語句在資料最後會轉換為select * from emp were deptno = 10 or dept= 20如果資料量很大,這種查詢效率很低的,應該exits 和not exits

10模糊查詢

查詢員工名字已M開頭的資訊

select * from emp where ename like 'M%'

sql中還提供了底線 _ 來匹配單個字元 ,這裡就不舉例子了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.