標籤:
一、登陸
SQL SERVER兩種登入方式的設定:Windows身份登入;SqlServer身份登入。
如何設定SQLServer身分識別驗證?
1.物件總管右擊--屬性--安全性--SqlServer和Windows身份登入。
2.物件總管--安全性--登入--sa--右擊--屬性--常規--設定密碼
3.物件總管--安全性--登入--sa--右擊--屬性--狀態--授予,啟用
重啟資料庫服務。
二、SQL語句 ( 增、刪、改、查)
1、增(兩種寫法)
insert into 表名(列名,列名,列名,...) values(值,值,值,....)
insert into 表名 values(值,值,值,值。。)
2、刪
delete from 表名 --刪除表內所有資料
delete from 表名 where 條件 --刪除合格語句
3、改
update 表名 set 列名=值,列名=值..... where 條件
4、查(重點)
查詢方式有很多種
(一)、簡單查詢
select*from 表名 ----基本形式(*代表所有列,*位置也可加列名)
(1)、投影
select 列名,列名,...from 表名
(二)、篩選
(1)、等值、不等值查詢
select * from 表名 where 列名=值 ---等值查詢
select * from 表名 where 列名 <> 值 --不等值查詢(<>相當於!=)
select * from 表名 where 列名 > 值>=
select * from 表名 where 列名 < 值<=
(2)、多條件查詢(邏輯與(and),邏輯或(or))
select * from 表名 where 條件1 and 條件2 ...
select * from 表名 where 條件1 or 條件2 ...
如果在where篩選條件中,既出現and又出現or,則先運算and。除非使用小括弧改變優
先級。
(3)、範圍查詢
select * from 表名 where 列名 >=範圍1 and 列名<=範圍2
例如:
select * from Car where Price >=30 and Price<=50
select * from Car where Price between 30 and 50
select * from Car where Oil=7.4 or Oil=8.5 or Oil=9.4
select * from Car where Oil in(7.4,8.5,9.4) --可以用where 列名 in(1,2,,,,)
(4)、模糊查詢
select * from 表名 where 列名 like ‘標識字%‘
%——任意多個任一字元
_——一個任一字元
例:
select * from Car where Name like ‘寶馬%‘
寶馬%——以寶馬開頭的
%寶馬——以寶馬結尾的
%寶馬%——只要含有寶馬這兩個字就可以。
__寶馬%——代表第三個字元以寶馬開頭的。
(5)、去重查詢:
select distinct 列名 from 表名 ——如果列中有重複值,則只查1個出來。
(6)、top 查詢
取前幾條資料
select top 數量 [列名|*] from 表名
(三)、排序
select * from 表名 where 條件 order by 列名 ASC|DESC,列名 ASC|DESC
例:
select * from car order by price asc ——預設是升序 ascending descending
select * from car order by price desc
select * from Car order by Oil asc,Price desc ——Oil主排序,Price次排序
(四)、分組
統計函數(彙總函式)
count(), max(), min(), sum(), avg()
count()統計總行數
count(*)得到所有的行數
count(列)得到該列中所有非null個數。
select COUNT(*) from car where Brand=‘b003‘
max(列) 這一列的最大,min(列)這一列的最小
select min(price) from car
sum(列)這一列的和,avg(列)這一列的平均
select AVG(price) from car
group by ...having...
1.group by後面跟的是列名。
2.一旦使用group by分組了,則select和from中間就不能用*,只能包含兩類東西一類是:group by 後面的列名,另一類是統計函數
select Oil,avg(price) from Car group by oil
對於統計函數產生的列,預設是無列名,可以通過下面的方法指定列名。
select Oil as 油耗,COUNT(*) as 數量,avg(price) 均價 from Car group by oil
having後面一般跟得是統計函數。它用來對分組後的資料進一步篩選。
(五)、複雜查詢
(1)、連結查詢:
第一步:求笛卡爾積
select * from Info,nation
第二步:根據兩個表相對應的列,對笛卡爾積進行有效資料的篩選。
select * from Info,Nation where Info.Nation = Nation.code
第三步:調整顯示要查詢的列
select Info.Code,Info.Name,Info.Sex,Nation.Name,Info.Birthday
from Info,nation where Info.Nation=Nation.Code
一般用join。。。on串連
select * from 表名1
join 表名2 on 表名1.列 = 表名2.列
join 表名3 on 表名2.列 = 表名3.列
....
where 查詢條件
左連(left join),右連(right join),全連(full join)
(2)、聯集查詢
把多個表的行合在一個介面視圖中。
用union把兩個查詢組合在一起。要求是這兩個查詢的列要一一對應。
(3)、子查詢(巢狀查詢)
(一)無關子查詢:
至少是兩層查詢,在外層查詢的裡面再寫查詢。
裡層查詢為外層查詢提供查詢的中間內容。
例:查詢“張旭“教師任課的學產生績。--成績、教師、課程都不在一個表中
select degree from score where cno=
(
select cno from course where tno=
(
select tno from teacher where tname=‘張旭‘
)
)
1月10日 SQL SERVER 增刪改查(第一節)