王利的博客
歷史在哪里扭曲,就在哪里突破 |
1.關鍵字
Top N 返回記錄的條數(shù),
top N percent? 返回查出結(jié)果數(shù)量的百分比(四舍五入),
with ties 與order by,top 一起用能夠查出和最后一條記錄相等的數(shù)據(jù),
distinct? 消除重復記錄
2.集合函數(shù)
Count(字段名) 統(tǒng)計數(shù)據(jù)忽略空行
count(*)? 統(tǒng)計不忽略空行,avg,max,min,sum
3.分類匯總查詢
Group by 子句按字段分類,相同字段為一組
注意:用于分類的字段必須是查詢的字段,不要對包含多個空值的字段使用,空值也會作為一組
Having 子句只能在group by 子句中使用作為條件判斷類似于where ,但where中不能調(diào)用聚合函數(shù),而having中可以.
4.Rollup 操作符
Cube 操作符
Compute 子句
Compute by 子句
5.聯(lián)接查詢
內(nèi)聯(lián)接查詢 : 返回滿足聯(lián)接條件的數(shù)據(jù)
表1 inner join 表2 on 聯(lián)接表達式
例:select distinct (lastname+' '+firstname) as name,orderid from employees as e inner join orders as o on e.employeeid=o.employeeid
外聯(lián)接查詢:返回滿足聯(lián)接條件的數(shù)據(jù),也返回左邊或者右邊表不符合聯(lián)接條件的記錄
左向外聯(lián)接:返回table1所有的記錄,如果table1中的記錄在table2中沒有匹配的記錄,則結(jié)果集和table2相關的字段為空值
Table1 left join table2 on 聯(lián)接expression
Table1 left outer join table2 on 聯(lián)接expression
右向外聯(lián)接:返回table2所有的記錄,如果table2中的記錄在table1中沒有匹配的記錄,則結(jié)果集和table1相關的字段為空值
Table1 right join table2 on 聯(lián)接expression
Table1 right outer table2 on 聯(lián)接expression
完整外聯(lián)接查詢:返回兩個表所有的記錄,互相沒有匹配記錄時填充空值.
Table1 full join table2 on 聯(lián)接expression
Table1 full outer table2 on 聯(lián)接expression
?
交叉聯(lián)接查詢:如果沒有where,返回table1,table2的笛卡兒乘積,既所有記錄的不同交叉組合
Table1 cross join table2
?
6.合并多個記錄集
Union? [all]操作符
要求引用的所有的表都有相似的數(shù)據(jù)結(jié)構(gòu),相同的字段數(shù)且每個查詢中字段的順序要相同
如果要全部返回不刪除重復記錄就使用all
盡量把復雜的查詢分解提高查詢效率.
?
7.子查詢
一個查詢語句嵌套在DML(select,update,delete,insert)語句中,則該語句被成為子查詢.嵌套最多32層,功能類似于聯(lián)接查詢,主要用于當查詢需要多個步驟時.
分類:
相關子查詢子查詢重復執(zhí)行,并將結(jié)果值代入外部查詢的where子句進行評估.
內(nèi)層子查詢被反復執(zhí)行,對外層查詢的每行內(nèi)層子查詢都執(zhí)行一次.
先外層查詢再內(nèi)層查詢再外層再內(nèi)層
例:select lastname,firstname from employees as e where '1998-1-1' in (select orderdate from orders as o where o.employeeid=e.employeeid)
相關子查詢的操作符 exists(not exists)用于限制外部查詢,使其結(jié)果集符合子查詢的條件,子查詢返回true ,false
例:select lastname,firstname from employees as e where exists (select * from orders as o where o.employeeid=e.e.employeeid and o.orderdate='1998-1-1')
嵌套子查詢? 只執(zhí)行一次子查詢并將結(jié)果值代入外部查詢的where子句進行評估.
內(nèi)層子查詢執(zhí)行完畢,再執(zhí)行外層查詢.
?例:select lastname,firstname from employees where employeesid in (select employeesid from orders where orders.orderdate='1998-1-1')
?
子查詢可以作為派生的表
可以作為表達式
Select? productname,unitprice,(unitprice-(select avg(unitprice) from products) ) as diff from products where productname='chai'
模擬聯(lián)接子句
模擬having子句