第14章 使用子查詢(xún)
14.1子查詢(xún)
簡(jiǎn)單查詢(xún):查詢(xún)單個(gè)數(shù)據(jù)表的select查詢(xún)語(yǔ)句驼仪。
子查詢(xún):嵌套在其他查詢(xún)中的查詢(xún)語(yǔ)句特姐。
14.2用子查詢(xún)過(guò)濾數(shù)據(jù)
即:子查詢(xún)的結(jié)果侈净,放在where后疯坤,作為過(guò)濾條件值肢簿。
例:列出訂購(gòu)TNT2貨品的所有客戶(hù)信息:
步驟分析:
a.通過(guò)貨品TNT2靶剑,在訂單貨品表中找到訂單編號(hào):select order_num from orderitems where prod_id='TNT2';
b.通過(guò)訂單編號(hào),在訂單表中找到客戶(hù)ID:select cust_id from orders where order_num in (20005,20007);
c.通過(guò)客戶(hù)ID译仗,在客戶(hù)表中找到客戶(hù)名稱(chēng)抬虽、聯(lián)系方式等信息:select cust_name,cust_contact from customers where cust_id in (10001,10004);
嵌套子查詢(xún),就是將a/b/c嵌套起來(lái):
select cust_name,cust_contact
from customers
where cust_id in (select cust_id
? ? ? ? ? ? ? ? ? ? ? ? ? ? from orders
? ? ? ? ? ? ? ? ? ? ? ? ? ? where order_num in (select order_num
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? from orderitems
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? where prod_id='TNT2'));
14.3作為計(jì)算字段使用子查詢(xún)
即:子查詢(xún)的結(jié)果纵菌,放在計(jì)算字段中阐污。
例:顯示客戶(hù)表中每個(gè)客戶(hù)的訂單總數(shù):
步驟分析:
a.客戶(hù)表的客戶(hù)id等于訂單表中的客戶(hù)id時(shí),在訂單表中計(jì)算訂單數(shù)量:
select cust_id,
? ? ? ? ? ?cust_name,
? ? ? ? ? ?cust_state,
? ? ? ? ? ?(select count(order_num)
? ? ? ? ? ? ?from orders
? ? ? ? ? ? ?where orders.cust_id=customers.cust_id) as order_count?
from customers?
order by cust_name;
上面的 orders.cust_id=customers.cust_id咱圆,表名與列名由句點(diǎn)分隔笛辟,叫做完全限定列名。
《mysql必知必會(huì)》是一本好書(shū)序苏,是一本sql語(yǔ)言入門(mén)書(shū)手幢,豆瓣評(píng)分很高。
作者是英國(guó)的Ben Forta忱详,世界知名的技術(shù)作家围来,由人民郵電出版社發(fā)行,我覺(jué)得原作名: MySQL Crash Course,直譯為:《MYSQL速成》更具暢銷(xiāo)書(shū)潛質(zhì)监透,只是比較俗吧桶错,呵呵。
書(shū)中從介紹簡(jiǎn)單的數(shù)據(jù)檢索開(kāi)始胀蛮,逐步深入一些復(fù)雜的內(nèi)容院刁,包括聯(lián)結(jié)的使用、子查詢(xún)粪狼、正則表達(dá)式和基于全文本的搜索退腥、存儲(chǔ)過(guò)程、游標(biāo)再榄、觸發(fā)器狡刘、表約束,等等不跟。
前三章是基礎(chǔ)概念颓帝,講了SQL和數(shù)據(jù)庫(kù)的基本概念米碰,Mysql數(shù)據(jù)庫(kù)的概念和使用方法窝革,第四章開(kāi)始SQL實(shí)操練習(xí),這里是本書(shū)的一些實(shí)操練習(xí)筆記吕座,有興趣的話(huà)可以按這個(gè)練習(xí)幾遍虐译,相信對(duì)新手會(huì)很有幫助,讓你不經(jīng)意間功力大增吴趴。