標籤:
關於Sql語句的學習,選擇的DBMS為SQL Server,Sql語句隨著工作中的應用不斷補充,不具備系統性,為個人筆記匯總,暫時用到的資料表如下:
- Student表中的CityCCode對應於City表中的Code欄位,為城市的英文字母縮寫;
1,INSERT TO 插入語句
INSERT TO語句用於向表格中插入新的記錄,如下:
1 insert into City(Code,CityCName) values(‘BJ‘,‘北京‘);2 insert into Student(CityCode,StuName) values(‘北京‘,‘SharpL‘);
2,DECLARE 聲明表變數
Sql語句的查詢中,總會涉及到多個表格的查詢,會用到子查詢,但是如果嵌套的層數過多,會使Sql語句難以閱讀和維護,子查詢Sql語句如下:
1 select Student.StuName from Student where CityCode in 2 (select Code from City where CityCName like ‘寧%‘)
上面的sql語句,在學生表中查詢,所有來自‘寧%‘(如寧波、寧夏等)的學生姓名,同樣的功能用declare語句聲明如下:
1 DECLARE @t table(Code varchar(10))2 insert into @t(Code) (select Code from City where CityCName like ‘寧%‘)3 select StuName from Student where CityCode in (select Code from @t)
其中@t為表變數,使用了暫存資料表,只包括Code一列。DECLARE 聲明表變數的方式在嵌套複雜時,優勢才能凸顯出來。
3,‘%’萬用字元&Like
上面的sql語句中用到了‘%’萬用字元,用來實現模糊查詢,百分比符號萬用字元是最常使用的萬用字元,表示任一字元出現任意次數。如上例,‘寧%’可以表示寧波、寧夏、寧靜等等。
為在搜尋子句中使用萬用字元,就必須使用LIKE操作符。如:CityCName like ‘寧%‘。Sql語句見2。
4,With as 添加子查詢部分
在’2‘中使用了聲明表變數的方法,但表變數實際上使用了暫存資料表,增加了額外的I/O開銷,SQL SERVER提供了CTE(即公用表運算式)來提高可讀性與效率,如下:
with A as(select Code from City where CityCName like ‘寧%‘)select StuName from Student where CityCode in (select Code from A)
上述Sql語句可以實現與2中的Sql語句一致的效果,更具體的With as 的使用方法請參考:使用WITH AS提高效能簡化嵌套SQL。
5,Except 求結果集的差
即從左查詢中返回右查詢中沒有找到的所有非重複值。
1 select CityCode from Student except2 (select CityCode from Student where CityCode like ‘N%‘)
注意是返回非重複值,也就是說如果Student表中存在多條來自上海的記錄,返回的CityCode只會包含一條SH,結果見:
基本Sql語句匯總