sql查詢語句基本框架 select col1,col2, ··· from tablename [where 條件] [group by ··· ] [having 篩選條件] [order by ··· ] [limit ··· ] 簡(jiǎn)單查詢 1. 查詢?nèi)啃小⒘校?) select * from 表名; 2. 別名(as,可省略)
select user_name as '名字',user_sex as '性別' from USER;
select name,sex from user as u ; 3. distinct 去掉重復(fù)值 select distinct nama from user; 4. limit
select * from user limit 1 ;——取第1條記錄 select * from user limit 2,5; ——取第3~7條記錄
條件查詢(where子句) select 列 from 表名 where 條件表達(dá)式 1. 比較運(yùn)算符(= , <> , > , >= , < , <= ) select * from user where age > 18; 2. 邏輯運(yùn)算符
select * from user where age > 18 and sex='女'; 3. between and (范圍查詢)
select * from user where name between ‘a(chǎn)mada’ and ‘king’; select * from user where age between 10 and 30; 4. 通配符(like)
select * from user where name like '孫_' ; ——以孫開頭,且只有兩個(gè)字的名字 select * from user where name like '孫%' ; ——任意以孫開頭的名字。 5. 查詢?yōu)榭?非空(NULL)
查詢結(jié)果排序(order by)
1. 按單行排序 select * from user [where ··· ] order by age desc;——查詢結(jié)果按age降序排列 2. 按多行排列
select * from 獎(jiǎng)牌表 order by 金牌數(shù) desc,銀牌數(shù) desc ,銅牌數(shù) desc; ——先按金牌數(shù)降序排序,金牌數(shù)相等的再按照銀牌數(shù)降序排列 分組匯總(group by) 聚合函數(shù)——對(duì)多條記錄進(jìn)行統(tǒng)計(jì) 常用的聚合函數(shù):
【eg】學(xué)生成績(jī)表scores(id,name,score) 查詢每個(gè)學(xué)生的總分、平均分、最高分 select id,sum(score),avg(score),max(score) from score group by id; 篩選分組結(jié)果(having)
【eg】成績(jī)表scores表(id,name,kecheng,score) 查詢平均成績(jī)大于90的學(xué)生的總成績(jī)、平均成績(jī): ①先分組統(tǒng)計(jì)每個(gè)學(xué)生的總成績(jī)、平均成績(jī) select id,sum(score),avg(score) from scores group by id; ②分組統(tǒng)計(jì)結(jié)果中,篩選出avg(score)大于90的 select id,sum(score),avg(score) from scores group by id having avg(score)>90 ; 連接查詢(join)
select col1,col2,... from table1 [left/right] join table2 on 連接條件(table1.col=table2.col) 1. 內(nèi)連接([inner] join)使用較多
2. 外連接(left/right join)
基礎(chǔ)表中的記錄在另一個(gè)表中沒有對(duì)應(yīng)數(shù)據(jù),也會(huì)返回 【eg】 表一:學(xué)生表stu(id,name) 表二:成績(jī)表score(id,scores) 查詢每個(gè)學(xué)生的name、scores: select id,name,scores from stu join score on stu.id = score.id ; 子查詢 子查詢的幾點(diǎn)說明:
單行子查詢的操作符: 、>、<、>=、<=、<>和!<> 多行子查詢的操作符:IN、ALL、ANY或函數(shù)min,max 1. 使用比較運(yùn)算符的子查詢
【eg】:stu表(id,name,score)中,查詢大于全班平均成績(jī)的同學(xué)id、name: select id,name from stu where score > (select avg(score) from stu ); 2. 使用in/not in關(guān)鍵字的子查詢 【eg】選課表course(stuid,coursename,stuname),查詢沒有選過“政治經(jīng)濟(jì)學(xué)”的學(xué)生 select stuid,stuname from course where stuid not in (select stuid from course where coursename='政治經(jīng)濟(jì)學(xué)'); 3. 使用exists關(guān)鍵字的子查詢 select ··· from ··· where exists (select ··· from ··· where ··· )
聯(lián)合查詢(union)
select .... from ... [where....] union [all] select .... from ... [where....] union [all] ......
本文主要為查詢部分,后續(xù)會(huì)繼續(xù)介紹有關(guān)數(shù)據(jù)類型、數(shù)據(jù)表操作、約束條件、函數(shù)等相關(guān)內(nèi)容。 |
|