sql外來鍵語句示範

來源:文萃谷 2.66W

篇一:經典SQL語句大全_主外來鍵_約束

sql外來鍵語句示範

一、基礎(建表、建約束、關係)

約束(Constraint)是Microsoft SQL Server 提供的自動保持資料庫完整性的一種方法,定義了可輸入表或表的單個列中的資料的限制條件(有關資料完整性的介紹請參見第9 章)。在SQL Server 中有5 種約束:約束(Primary Key Constraint)、外關鍵字約束(Foreign Key Constraint)、惟一性約束(Unique Constraint)、檢查約束(Check Constraint)和預設約束(Default Constraint)。

(最後幾頁介紹SQL基礎 約束)

1、說明:建立資料庫

CREATE DATABASE database-name

2、說明:刪除資料庫

drop database dbname

3、說明:備份sql server

--- 建立 備份資料的 device

USE master

EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_'

--- 開始 備份

BACKUP DATABASE pubs TO testBack

4、說明:建立新表

create table tabname(col1 type1 [not null] [primary key],col2 type2

[not null],..)

--建表、建約束、關係

create table tableok

col1 int, col2_notnull int not null,

col3_default n1) not null default('男'),

--預設男

col4_default datetime not null default(getdate()),

--預設得到系統時間

col5_checkintnot null check(col5_check>=18 and col5_check<=

55), --新增約束,資料值在18到55之間

col6_checkn9) not null check(col6_check like 'msd0902[0-9][^6-9]'),

--新增約束,資料值前7位必須是‘msd0902’,倒數第兩位可以是0-9中任意一個數字,最後一位不是6-9之間的數字。

cola_primary n5) not null primary key,

--建立主鍵

colb_unique int unique,

--唯一約束

col7_Identity int not null identity(100,1),

--自增長,從100開始,每列值增加1個

col8_identity numeric(5,0) not null identity(1,1)

--自增長,從1開始,每列值增加1個,最大值是5位的整數

col9_guid uniqueidentifier not null default(newid())

--使用newid()函式,隨機獲取列值)

--alter

--主外來鍵/引用/關係 約束

alter table 從表名 [with check]--啟用 with nocheck--禁用約束 add constraint FK_主表名_從表名

foreign key (從表中的欄位名) references 主表名 (主表中的欄位名)

--其它非主外來鍵約束

alter table wf

add constraint 約束名 約束型別 具體的約束說明

alter table wf--修改聯合主鍵

add constraint Pk_cola_primary primary key(cola_primary,col1)

根據已有的表建立新表:

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

B:create table tab_new as select col1,col2? from tab_old definition only

5、說明:刪除新表

tabname

6、說明:增加一個列

Alter table tabname add column col type

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

7、說明:新增主鍵: Alter table tabname add primary key(col) 說明:刪除主鍵: Alter table tabname drop primary key(col)

8、說明:建立索引:create [unique] index idxname on tabname(col?.) 刪除索引:drop index idxname

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

9、說明:建立檢視:create view viewname as select statement 刪除檢視:drop view viewname

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

選擇:select * from table1 where 範圍

插入: into table1(field1,field2) values(value1,value2) 刪除: from table1 where 範圍

更新:table1 set field1=value1 where 範圍

查詢:select * from table1 where field1 like ’%value1%’

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

總數:select count as totalcount from table1

求和:select sum(field1) as sumvalue from table1

平均:select avg(field1) as avgvalue from table1

最大:select max(field1) as maxvalue from table1

最小:select min(field1) as minvalue from table1

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

A: UNION 運算子

UNION 運算子通過組合其他兩個結果表(例如 TABLE1 和 TABLE2)並消去表中任何重複行而派生出一個結果表。當 ALL 隨 UNION 一起使用時(即 UNION ALL),不消除重複行。兩種情況下,派生表的每一行不是來自 TABLE1 就是來自 TABLE2。

B: EXCEPT 運算子

EXCEPT 運算子通過包括所有在 TABLE1 中但不在 TABLE2 中的行並消除所有重複行而派生出一個結果表。當 ALL 隨 EXCEPT 一起使用時 (EXCEPT ALL),不消除重複行。

C: INTERSECT 運算子

INTERSECT 運算子通過只包括 TABLE1 和 TABLE2 中都有的行並消除所有重複行而派生出一個結果表。當 ALL 隨 INTERSECT 一起使用時 (INTERSECT ALL),不消除重複行。

注:使用運算詞的幾個查詢結果行必須是一致的。

12、說明:使用外連線

A、left (outer) join:

左外連線(左連線):結果集幾包括連線表的匹配行,也包括左連線表的所有行。

SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

B:right (outer) join:

右外連線(右連線):結果集既包括連線表的匹配連線行,也包括右連線表的所有行。

C:full/cross (outer) join:

全外連線:不僅包括符號連線表的匹配行,還包括兩個連線表中的所有記錄。

分組:Group by:

一張表,一旦分組 完成後,查詢後只能得到組相關的資訊。

組相關的資訊:(統計資訊) count,sum,max,min,avg 分組的.標準) 在SQLServer中分組時:不能以text,ntext,image型別的欄位作為分組依據

在selecte統計函式中的欄位,不能和普通的欄位放在一起;

13、對資料庫進行操作:

分離資料庫: sp_detach_db; 附加資料庫:sp_attach_db 後接表明,附加需要完整的路徑

14.如何修改資料庫的名稱:

sp_renamedb 'old_name', 'new_name'

二、提升

1、說明:複製表(只複製結構,源表名:a 新表名:b) (Access可用) 法一:select * into b from a where 1<>1(僅用於SQlServer)

法二:select top 0 * into b from a

2、說明:拷貝表(拷貝資料,源表名:a 目標表名:b) (Access可用) into b(a, b, c) select d,e,f from b;

3、說明:跨資料庫之間表的拷貝(具體資料使用絕對路徑) (Access可用) into b(a, b, c) select d,e,f from b in ‘具體資料庫’ where 條件

例子: b in '"&Server.MapPath(".")&"" &"' where..

4、說明:子查詢(表名1:a 表名2:b)

select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)

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

select e,name,ate from table a,(select max(adddate) adddate from table where e=e) b

6、說明:外連線查詢(表名1:a 表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、說明:線上檢視查詢(表名1:a )

select * from (SELECT a,b,c FROM a) T where t.a > 1;

8、說明:between的用法,between限制查詢資料範圍時包括了邊界值,not between不包括

select * from table1 where time between time1 and time2

select a,b,c, from table1 where a not between 數值1 and 數值2

9、說明:in 的使用方法

select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

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

from table1 where not exists ( select * from table2 where d1=d1 )

11、說明:四表聯查問題:

select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

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

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

13、說明:一條sql 語句搞定資料庫分頁

select top 10 b.* from (select top 20 主鍵欄位,排序欄位 from 表名 order by 排序欄位 desc) a,表名 b where b.主鍵欄位 = a.主鍵欄位 order by a.排序欄位 具體實現:

關於資料庫分頁:

declare @start int,@end int

@sql nvar600)

set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’

exec sp_executesql @sql

注意:在top後不能直接跟一個變數,所以在實際應用中只有這樣的進行特殊的處理。Rid為一個標識列,如果top後還有具體的欄位,這樣做是非常有好處的。因為這樣可以避免 top的欄位如果是邏輯索引的,查詢的結果後實際表中的不一致(邏輯索引中的資料有可能和資料表中的不一致,而查詢時如果處在索引則首先查詢索引) 14、說明:前10條記錄

select top 10 * form table1 where 範圍

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

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

16、說明:包括所有在 TableA 中但不在 TableB和TableC 中的行並消除所有重複行而派生出一個結果表

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

17、說明:隨機取出10條資料

select top 10 * from tablename order by newid()

18、說明:隨機選擇記錄

select newid()

熱門標籤