mysql的查詢、子查詢及連接查詢

一、mysql查詢的五種子句

where(條件查詢)、having(篩選)、group by(分組)、order by(排序)、limit(限制結果數)

1、where常用運算符:

比較運算符

> , ?< ,= ?, != (< >),>= ? , ? <=

in(v1,v2..vn)

between v1 and v2 ? ?在v1至v2之間(包含v1,v2)

邏輯運算符

not ( ! ) ?邏輯非

or ( || ) ? ?邏輯或

and ( && ) ?邏輯與

where price>=3000 and price <= 5000 or price >=500 and price <=1000

取500-1000或者3000-5000的值

where price not between 3000 and 5000

不在3000與5000之間的值

模糊查詢

like 像

通配符:

% ?任意字符

_ ? 單個字符

where goods_name like '諾基亞%'

where goods_name like '諾基亞N__'

2、group by 分組

一般情況下group需與統計函數(聚合函數)一起使用才有意義

如:select goods_id,goods_name,cat_id,max(shop_price) from goods group by cat_id;

這里取出來的結果中的good_name是錯誤的!因為shop_price使用了max函數,那么它是取最大的,而語句中使用了group by 分組,那么goods_name并沒有使用聚合函數,它只是cat_id下的第一個商品,并不會因為shop_price改變而改變

mysql中的五種統計函數:

(1)max:求最大值

select max(goods_price) from goods

這里會取出最大的價格的值,只有值

#查詢每個欄目下價格最高的

select cat_id,max(goods_price) from goos group by cat_id;

#查出價格最高的商品編號

select goods_id,max(goods_price) from goods group by goods_id;

(2)min:求最小值

(3)sum:求總數和

#求商品庫存總和

select sum(goods_number) from goods;

(4)avg:求平均值

#求每個欄目的商品平均價格

select cat_id,avg(goods_price) from goods group by cat_id;

(5)count:求總行數

#求每個欄目下商品種類

select cat_id,count(*) from goods group by cat_id;

###要把每個字段名當成變量來理解,它可以進行運算###

例:查詢本店每個商品價格比市場價低多少;

select goods_id,goods_name,goods_price-market_price from goods;

查詢每個欄目下面積壓的貨款

select cat_id,sum(goods_price*goods_number) from goods group by cat_id;

###可以用as來給計算結果取個別名###

select cat_id,sum(goods_price * goods_number) ?as hk from goods group by cat_id

不僅列名可以取別名,表單也可以取別名

3、having 與where 的異同點

having與where類似,可以篩選數據,where后的表達式怎么寫,having后就怎么寫

where針對表中的列發揮作用,查詢數據

having對查詢結果中的列發揮作用,篩選數據

#查詢本店商品價格比市場價低多少錢,輸出低200元以上的商品

select goods_id,good_name,market_price - shop_price as s from goods having s>200 ;

//這里不能用where因為s是查詢結果,而where只能對表中的字段名篩選

如果用where的話則是:

select goods_id,goods_name from goods where market_price - shop_price > 200;

#同時使用where與having

select cat_id,goods_name,market_price - shop_price as s from goods where cat_id = 3 having s > 200;

#查詢積壓貨款超過2萬元的欄目,以及該欄目積壓的貨款

select cat_id,sum(shop_price * goods_number) as t from goods group by cat_id having s > 20000

#查詢兩門及兩門以上科目不及格的學生的平均分

思路:

#先計算所有學生的平均分

select name,avg(score) as pj from stu group by name;

#查出所有學生的掛科情況

select name,score<60 from stu;

#這里score<60是判斷語句,所以結果為真或假,mysql中真為1假為0

#查出兩門及兩門以上不及格的學生

select name,sum(score<60) as gk from stu group by name having gk > 1;

#綜合結果

select name,sum(score<60) as gk,avg(score) as pj from stu group by name having gk >1;

4、order by

(1) order by price ?//默認升序排列

(2)order by price desc //降序排列

(3)order by price asc //升序排列,與默認一樣

(4)order by rand() //隨機排列,效率不高

#按欄目號升序排列,每個欄目下的商品價格降序排列

select * from goods where cat_id !=2 order by cat_id,price desc;

5、limit

limit [offset,] N

offset 偏移量,可選,不寫則相當于limit 0,N

N ? ? 取出條目

#取價格第4-6高的商品

select good_id,goods_name,goods_price from goods order by good_price desc limit 3,3;

###查詢每個欄目下最貴的商品

思路:

#先對每個欄目下的商品價格排序

select cat_id,goods_id,goods_name,shop_price from goods order by cat_id,shop_price desc;

#上面的查詢結果中每個欄目的第一行的商品就是最貴的商品

#把上面的查詢結果理解為一個臨時表[存在于內存中]【子查詢】

#再從臨時表中選出每個欄目最貴的商品

select * from (select goods_id,goods_name,cat_id,shop_price from goods order by cat_id,shop_price desc) as t group by cat_id;

#這里使用group by cat_id是因為臨時表中每個欄目的第一個商品就是最貴的商品,而group by前面沒有使用聚合函數,所以默認就取每個分組的第一行數據,這里以cat_id分組

良好的理解模型:

1、where后面的表達式,把表達式放在每一行中,看是否成立

2、字段(列),理解為變量,可以進行運算(算術運算和邏輯運算)

3、 取出結果可以理解成一張臨時表

二、mysql子查詢

1、where型子查詢

(把內層查詢結果當作外層查詢的比較條件)

#不用order by 來查詢最新的商品

select goods_id,goods_name from goods where goods_id = (select max(goods_id) from goods);

#取出每個欄目下最新的產品(goods_id唯一)

select cat_id,goods_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id);

2、from型子查詢

(把內層的查詢結果供外層再次查詢)

#用子查詢查出掛科兩門及以上的同學的平均成績

思路:

#先查出哪些同學掛科兩門以上

select name,count(*) as gk from stu where score < 60 having gk >=2;

#以上查詢結果,我們只要名字就可以了,所以再取一次名字

select name from (select name,count(*) as gk from stu having gk >=2) as t;

#找出這些同學了,那么再計算他們的平均分

select name,avg(score) from stu where name in (select name from (select name,count(*) as gk from stu having gk >=2) as t) group by name;

3、exists型子查詢

(把外層查詢結果拿到內層,看內層的查詢是否成立)

#查詢哪些欄目下有商品,欄目表category,商品表goods

select cat_id,cat_name from category where exists(select * from goods where goods.cat_id = category.cat_id);

三、union的用法

(把兩次或多次的查詢結果合并起來,要求查詢的列數一致,推薦查詢的對應的列類型一致,可以查詢多張表,多次查詢語句時如果列名不一樣,則取第一次的列名!如果不同的語句中取出的行的每個列的值都一樣,那么結果將自動會去重復,如果不想去重復則要加all來聲明,即union all)

## 現有表a如下

id ?num

a ? ?5

b ? ?10

c ? ?15

d ? ?10

表b如下

id ?num

b ? ?5

c ? ?10

d ? ?20

e ? ?99

求兩個表中id相同的和

select id,sum(num) from (select * from taunionselect * from tb) as tmp group by id;

//以上查詢結果在本例中的確能正確輸出結果,但是,如果把tb中的b的值改為10以查詢結果的b的值就是10了,因為ta中的b也是10,所以union后會被過濾掉一個重復的結果,這時就要用union all

select id,sum(num) from (select * from taunion allselect * from tb) as tmp group by id;

#取第4、5欄目的商品,按欄目升序排列,每個欄目的商品價格降序排列,用union完成

select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4 union?select goods_id,goods_name,cat_id,shop_price from goods where cat_id=5 order by cat_id,shop_price desc;

【如果子句中有order by 需要用( ) 包起來,但是推薦在最后使用order by,即對最終合并后的結果來排序】

#取第3、4個欄目,每個欄目價格最高的前3個商品,結果按價格降序排列

(select goods_id,goods_name,cat_id,shop_price from goods where cat_id=3 order by shop_price desc limit 3) union??(select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4 order by shop_price desc limit 3) order by shop_price desc;

四、左連接,右連接,內連接

現有表a有10條數據,表b有8條數據,那么表a與表b的笛爾卡積是多少?

select * from ta,tb ? //輸出結果為8*10=80條

1、左連接

以左表為準,去右表找數據,如果沒有匹配的數據,則以null補空位,所以輸出結果數>=左表原數據數

語法:select n1,n2,n3 from taleft jointbonta.n1= ta.n2 [這里on后面的表達式,不一定為=,也可以>,<等算術、邏輯運算符]【連接完成后,可以當成一張新表來看待,運用where等查詢

#取出價格最高的五個商品,并顯示商品的分類名稱

select goods_id,goods_name,goods.cat_id,cat_name,shop_price from goods left join category on goods.cat_id = category.cat_id order by ?shop_price desc limit 5;

2、右連接

a left join b 等價于 b right join a

推薦使用左連接代替右連接

語法:select n1,n2,n3 from taright jointbonta.n1= ta.n2

3、內連接

查詢結果是左右連接的交集,【即左右連接的結果去除null項后的并集(去除了重復項)】

mysql目前還不支持 外連接(即左右連接結果的并集,不去除null項)

語法:select n1,n2,n3 from tainner jointbonta.n1= ta.n2

#########

例:現有表a

name ?hot

a ? ? ? ?12

b ? ? ? ?10

c ? ? ? ?15

表b:

name ? hot

d ? ? ? ?12

e ? ? ? ?10

f ? ? ? ? 10

g ? ? ? ?8

表a左連接表b,查詢hot相同的數據

select a.*,b.* from aleft joinb on a.hot = b.hot

查詢結果:

name ?hot ? name ?hot

a ? ? ? 12 ? ? d ? ? ? 12

b ? ? ? 10 ? ? e ? ? ? 10

b ? ? ? 10 ? ? f ? ? ? ?10

c ? ? ? 15 ? ? null ? ?null

從上面可以看出,查詢結果表a的列都存在,表b的數據只顯示符合條件的項目

再如表b左連接表a,查詢hot相同的數據

select a.*,b.* from bleft joina on a.hot = b.hot

查詢結果為:

name ?hot ? name ?hot

d ? ? ? 12 ? ? a ? ? ? 12

e ? ? ? ?10 ? ?b ? ? ? 10

f ? ? ? ?10 ? ? b ? ? ?10

g ? ? ? ?8 ? ? null ? ?null

再如表a右連接表b,查詢hot相同的數據

select a.*,b.* from aright joinb on a.hot = b.hot

查詢結果和上面的b left join a一樣

###練習,查詢商品的名稱,所屬分類,所屬品牌

select goods_id,goods_name,goods.cat_id,goods.brand_id,category.cat_name,brand.brand_name from goods left join category on goods.cat_id = category.cat_id left join brand on goods.brand_id = brand.brand_id limit 5;

理解:每一次連接之后的結果都可以看作是一張新表

###練習,現創建如下表

createtablem(

idint,

zidint,

kidint,

resvarchar(10),

mtimedate

) charset utf8;

insertintomvalues

(1,1,2,'2:0','2006-05-21'),

(2,3,2,'2:1','2006-06-21'),

(3,1,3,'2:2','2006-06-11'),

(4,2,1,'2:4','2006-07-01');

createtablet

(tidint,tnamevarchar(10)) charset utf8;

insertintotvalues

(1,'申花'),

(2,'紅牛'),

(3,'火箭');

要求按下面樣式打印2006-0601至2006-07-01期間的比賽結果

樣式:

火箭 ? 2:0 ? ?紅牛 ?2006-06-11

查詢語句為:

select zid,t1.tname as t1name,res,kid,t2.tname as t2name,mtime?from m left join t as t1 on m.zid = t1.tid

left join t as t2 on m.kid = t2.tid?where mtime between '2006-06-01' and '2006-07-01';

總結:可以對同一張表連接多次,以分別取多次數據

轉載:http://www.cnblogs.com/rollenholt/archive/2012/05/15/2502551.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內容

  • mysql的查詢、子查詢及連接查詢 一、mysql查詢的五種子句 where(條件查詢)、having(篩選)、g...
    時芥藍閱讀 681評論 0 3
  • 數據庫基礎知識 數據庫客戶端MySQL作為數據庫服務器來運行,任何滿足mysql通信規范的軟件都可以作為客戶端來連...
    littlexjing閱讀 913評論 0 2
  • 我時不時跟小胖說,“你要做功課咯~”,意味著他很久沒說“我愛你”。其實,我并不是需要甜言蜜語的小女生,我懂得從對方...
    黃家小妞閱讀 1,272評論 0 0
  • 你說你臉大,你要用手遮一下。其實,在我眼里你猶如女神一樣的存在哦~~不過,我從未對你說過這樣的話,因為我覺得你不會...
    劉翰字閱讀 415評論 0 1
  • 感恩父母養育之恩愿母親身體健康衣食無憂智慧增長!感恩母親含辛茹苦把我們兄弟五人拉扯大!感恩母親現在反復說同樣的話磨...
    T上善若水閱讀 171評論 0 0