1. 程式人生 > >sql精妙語句整理

sql精妙語句整理

一、SQL分類:

DDL資料定義語言(Create,Alter,Drop,DECLARE)

建立資料庫、表格,修改表格,刪除資料庫表格、建立、修改、刪除查詢指令,刪除資料表內容

DML—資料操縱語言(Select,Delete,Update,Insert)

DCL—資料控制語言(GRANT,REVOKE,COMMIT,ROLLBACK)

是用來設定或更改資料庫使用者或角色許可權的語句,包括(grant,deny等)語句。在預設狀態下,只有sysadmin,dbcreator,db_owner或db_securityadmin等人員才有權力執行DCL

二、DDL—資料定義語言

1、說明:建立資料庫

Create DATABASE database-name

2、說明:刪除資料庫

drop database dbname

3、說明:備份oracle

資料庫模式:
EXP SYSTEM/[email protected] FULL = YFILE = 'DB081222.DMP' LOG = 'DB081222.LOG'
使用者模式:
EXP USER/[email protected] FILE ='USER081222.DMP' LOG = 'USER081222.LOG'
表模式:
EXP USER/[email protected]ACLE FILE ='USER081222.DMP' LOG = 'USER081222.LOG' TABLES = ('TABLE_1','TABLE_2')

4、說明:建立新表

create tabletabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

根據已有的表建立新表:

A:create table tab_new like tab_old (使用舊錶建立新表)

B:create table tab_new as selectcol1,col2… from tab_old definition only

5、說明:刪除新表drop table tabname

6、說明:增加一個列

Alter table tabnameadd column col type

注:列增加後將不能刪除。DB2中列加上後資料型別也不能改變,唯一能改變的是增加varchar型別的長度。

7、說明:新增主鍵: Alter table tabname addprimary key(col)

說明:刪除主鍵: Altertable tabname drop primary key(col)

8、說明:建立索引:create [unique] index idxnameon tabname(col….)

刪除索引:dropindex idxname

注:索引是不可更改的,想更改必須刪除重新建。

9、說明:建立檢視:create view viewname as selectstatement

刪除檢視:drop viewviewname

10、說明:幾個簡單的基本的sql語句

選擇:select* from table1 where 範圍

插入:insertinto table1(field1,field2) values(value1,value2)

刪除:deletefrom table1 where 範圍

更新:updatetable1 set field1=value1 where 範圍

查詢:select* from table1 where field1 like ’%value1%’ ---like的語法很精妙,查資料!

排序:select* from table1 order by field1,field2 [desc]

總數:selectcount * as totalcount from table1

求和:selectsum(field1) as sumvalue from table1

平均:selectavg(field1) as avgvalue from table1

最大:selectmax(field1) as maxvalue from table1

最小:selectmin(field1) as minvalue from table1

1、連結查詢  

說明:幾個高階查詢運算詞

A、left join: 左連線

LEFT JOIN 關鍵字會從左表 (table_name1) 那裡返回所有的行,即使在右表 (table_name2) 中沒有匹配的行。

select column_name(s)

from table_name1

left join table_name2

ontable_name1.column_name=table_name2.column_name

B:right join:

RIGHT JOIN關鍵字會從右表(table_name2) 那裡返回所有的行,即使在左表 (table_name1) 中沒有匹配的行。

select column_name(s)

from table_name1

right join table_name2

ontable_name1.column_name=table_name2.column_name

C:full join:

只要其中某個表存在匹配,FULL JOIN 關鍵字就會返回行。

select column_name(s)

from table_name1

full join table_name2

on table_name1.column_name=table_name2.column_name

2、如何使用sql把兩張欄位不相同的表合成欄位相同的一張表

select   A as a,B as b   from  table1
union   all
select   d as a,c as b   from   table2

結果:a b

3、返回表中某列的唯一值--- DISTINCT 關鍵詞

select distinct company from orders

4、where字句

AND OR 可在 WHERE 子語句中把兩個或多個條件結合起來。

5、order by語句用於根據指定的列對結果集進行排序。

Asc預設升序,desc降序

6、萬用字元

例子:

查詢居住在以"Ne" 開始的城市裡的人:select * from persons where city like 'ne%'

查詢居住在包含 "lond" 的城市裡的人:select * from persons where city like '%lond%'

查詢名字的第一個字元之後是"eorge" 的人:select * from persons where firstname like '_eorge'

查詢的這條記錄的姓氏以 "C" 開頭,然後是一個任意字元,然後是 "r",然後是任意字元,然後是 "er":select * from persons where lastname like 'c_r_er'
查詢居住的城市以 "A" 或 "L" 或 "N" 開頭的人:select * from persons where city like '[aln]%'
居住的城市不以 "A" 或 "L" 或 "N" 開頭的人:select * from persons where city like '[!aln]%'

7、使用EXISTS句代替in語句

操作符允許我們在 WHERE 子句中規定多個值。
select column_name(s)
from table_name
where column_name exists (value1,value2,...)

8、操作符 between ... and 會選取介於兩個值之間的資料範圍。

這些值可以是數值、文字或者日期

9、GROUP BY 語句用於結合合計函式,根據一個或多個列對結果集進行分組。分組返回一條記錄

group by 一列
select customer,sum(orderprice) from orders group by customer
select customer,orderdate,sum(orderprice) from orders
group by customer,orderdate
group by原則
就是 select 後面的所有列中,沒有使用聚合函式的列,必須出現在 group by 後面
和having區別

查詢table表查詢每一個班級中年齡大於20,性別為男的人數

select COUNT(*)as '>20歲人數',classid  from Table1 where sex='男' group by classid,age having age>20

--需要注意說明:當同時含有where子句、group by 子句 、having子句及聚集函式時,執行順序如下:

--執行where子句查詢符合條件的資料;

--使用groupby 子句對資料進行分組;對group by 子句形成的組執行聚集函式計算每一組的值;最後用having 子句去掉不符合條件的組。

--having 子句中的每一個元素也必須出現在select列表中。有些資料庫例外,如oracle.

--having子句和where子句都可以用來設定限制條件以使查詢結果滿足一定的條件限制。

--having子句限制的是組,而不是行。where子句中不能使用聚集函式,而having子句中可以。

10、Except    比較兩個查詢的結果,返回非重複值。

 (select a from tableA ) except (select a fromtableB) except (select a from tableC)

返回A  B  C表中不重複的值

11、oracle case when then else end   一旦滿足了某一個WHEN ,則這一條資料就會退出CASE WHEN,而不再考慮其他CASE

CASE WHEN 表示式有兩種形式

--簡單Case函式 

CASEsex 

WHEN'1' THEN '男' 

WHEN'2' THEN '女' 

ELSE'其他'END 

--Case搜尋函式 

CASE

WHENsex = '1' THEN '男' 

WHENsex = '2' THEN '女' 

ELSE'其他'END 

使用場合例子1


使用場合例子2
使用場合3

12、select into 語句從一個表中選取資料,然後把資料插入另一個表中。

說明:複製表(只複製結構,源表名:a 新表名:b)

select * into b froma where 1<>1

說明:拷貝表(拷貝資料,源表名:a 目標表名:b)

 insert into b(a, b, c) select d,e,f from b;

說明:跨資料庫之間表的拷貝(具體資料使用絕對路徑)

 insert into b(a, b, c) select d,e,f from b in ‘具體資料庫’ where 條件

例子:..from b in'"&Server.MapPath(".")&"\data.mdb"&"' where..

五、oracle資料型別

六、DML---函式

1、聚合函式

max():返回一列中的最大值。NULL 值不包括在計算中。

select max(column_name) from table_name

min(): 函式返回一列中的最小值。NULL 值不包括在計算中。

select min(column_name) from table_name

sum()函式返回數值列的總數(總額)。

select sum(column_name) from table_name

last() :函式返回指定的欄位中最後一個記錄的值。

select last(column_name) from table_name

first() :函式返回指定的欄位中第一個記錄的值。

select first(column_name) from table_name

count() :函式返回匹配指定條件的行數。

函式返回指定列的值的數目(null 不計入):

select count(column_name) from table_name

count(*) 函式返回表中的記錄數:

select count(*) from table_name

avg()函式返回數值列的平均值。null 值不包括在計算中。

select avg(column_name) from table_name

2、字元函式

lower():字串變成小寫select lower('abcde') from dual ;

upper():將字串變成大寫  select upper('abcd') from dual ;

initcap():將每個字串首字母大寫select initcap(lower(ename)) from emp;  函式可以巢狀

concat()函式:(可以連線兩個字串)select concat('hello',' world!!!') from dual ;

實際上使用“||”也可以完成兩個字串的連線操作。

substr()函式:(字串擷取)

擷取的時候需要注意:要從那裡開始擷取,之後取多長的長度。select substr('hello',1,2) from dual ;

同時也可以取負數 ,表示從尾倒著取。select substr('hello',-3,2)from dual 倒數第三個開始取兩位

注意:substr函式的開始點是從1或0開始的,oracle非常智慧。

length():取出字串的長度,取出每一個僱員的姓名的長度:select ename||' 姓名的長度為:'||length(ename)from emp ;

instr()函式:查詢在一個字串中是否有指定的字串,如果有,則返回其位置

selectinstr('hello','x') from dual ;
       
如果有此字串,則返回位置,如果沒有,則返回0

trim()函式:去掉左右空格的函式       selecttrim('        hello          ')from dual ;

查詢:
 (1)、 檢索姓名最後一個字母為n的僱員
        • select * from emp wheresubstr(ename,-1,1)='n';
 (2)、 檢索職務為“sale”的全部員工資訊
      • select * from emp wheresubstr(job,1,4)='sale';

3、數值函式

round()函式:(表示四捨五入)

      •select round(34.56) from dual;     結果:35
      •select round(34.56,-1) from dual ;  結果:30

      •select round(35.56,-1) from dual ;  結果:40

      •select round(34.56,1) from dual ;   結果:35.6
trunc()函式:(表示擷取函式,不會保留任何小數且不會執行四捨五入的操作)     • select trunc(34.56) from dual;     結果:34

     • select trunc(34.56,1) from dual ;   結果:34.5
     • select trunc(34.56,-1) from dual ;  結果:30

mod()函式:(取餘數,即取模)      •select mod(10,3) from dual;        結果:1

4、日期函式

sysdate取得當前的日期:
select sysdate fromdual ;

     日期-數字=日期;日期+數字=日期;日期-日期=數字(多少天)

   例如:計算10部門中的員工進入公司的週數:
      肯定使用當前日期-僱傭日期(hiredate) = 天數,天數/7為日期數。
      select ename,round((sysdate-hiredate)/7) from emp ;
  months_between()函式:給出指定日期範圍的月數

      求出所有員工的受僱月數:months_between,使用當前日期與僱傭日期比較。

      select ename,round(months_between(sysdate,hiredate))from emp ;

  add_months()函式:在指定的日期上加上指定的月數,求出之後的日期

      求出,三個月之後的日期是那一天:
      select add_months(sysdate,3) from dual ;

   next_day():表示下一個今天(星期幾)select next_day(sysdate,'星期一')from dual ; 表示下一個星期一是多少號

   last_day:求出當前日期所在月的最後一天:      select last_day(sysdate) from dual;            表示本月的最後一天的日期

6、通用函式

nvl(ex0,ex1)函式:將一個指空值變為一個指定的內容

nvl2(ex0,ex1,ex2)函式

select nvl2(null,’123’,’11111’)from dual;

如果不為空返回123,為空返回11111

nullif(ex1,ex2)

比較兩個表示式,如果值相等返回空,否則返回ex1表示式

decode函式:類似於if else if else 語句

select decode(1,1,'內容為1',2,'內容為2',3,'內容為3') from dual;

如果給出的值為1,那麼則顯示內容為1 ,為2則顯示內容為2…… 

    再例如 如果工作為銷售則顯示銷售員、若為業務員則顯示業務員、若為總裁則顯示總裁

select decode(job,'salseman','銷售員','clerk','業務員','president','總裁') from emp!

start with  connect by 語法結構如上面說看到的 例子, 其語法結構為  start with condition  connect by  condition (含 prior 關鍵字)
start with conditon 給出的seed 資料的範圍, connect by  後面給出了遞迴查詢的條件,prior 關鍵字表示父資料,prior 條件表示子資料需要滿足父資料的什麼條件。

七、常用SQL語句蒐集

1、說明:顯示文章、提交人和最後回覆時間

selecta.title,a.username,b.adddate from table a,(select max(adddate) adddate fromtable where table.title=a.title) b

2、刪除重複記錄group by having一起使用最好。

引自:

內容相同,主鍵id不同,保留主鍵id最大的一條記錄,(group   by   子句後跟的欄位就是你用來判斷重複的欄位)

Delete fromtablename where id not in (select max(id) from tablename group bycol1,col2,...)

判斷表中所有欄位相同也可以這樣寫

3、說明:兩張關聯表,刪除主表中已經在副表中沒有的資訊

delete from table1where not exists ( select * from table2 where table1.field1=table2.field1 )

4、說明:四表聯查

select * from a leftinner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.dwhere .....

5、說明:日程安排提前五分鐘提醒

select * from 日程安排 where datediff('minute',f開始時間,getdate())>5

6、說明:資料分頁查詢

select * from(

select rownumrn,t.OWNER,t.OBJECT_NAME,t.OBJECT_ID from test_big t

where rownum <=100)

where rn >= 1;

7、說明:選擇在每一組b值相同的資料中對應的a最大的記錄的所有資訊(類似這樣的用法可以用於論壇每月排行榜,每月熱銷產品分析,按科目成績排名,等等.)

select a,b,c fromtablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)