上課筆記MySQL數據庫小知識

單表查詢:

1選擇列

select * from xs;

select 學號,姓名 from xs;

select 學號 as sno,姓名  as name  from xs;

select 學號,總學分*1.2 as 新學分 from xs;

select 姓名,case

when 性別=1 then ''

when 性別=0 then ''

end  as 性別,專業名

from xs;

2  選擇行 

where條件

1)比較運算符:= >  >=   <   <=  <>   !=  <=>

2) 邏輯運算符    and   &&     or  ||  not  !

查找計算機系的男學生的信息

select * from xs  where  專業名='計算機' and  性別=1

3)模式匹配:like    %   _

select * from xs where 姓名 like '%';                  '_'

4)範圍比較

between  :成績 between 80 and 90     (成績 >=80  and 成績<=90)

not  between   :  select * from xs_kc  where  成績  not between  80 and 90

查看產地是廣州,上海,北京的產品信息

select * from product 

where 產地='廣州' or 產地='上海' or  產地='北京';

in:     產地  in ('廣州','上海','北京')

查看關鍵字與列表中的任何一個值匹配,就返回true

not in:      產地 not in ('廣州','上海','北京')

5)空值比較

is  null

is not null

select * from xs where 備註 is not null;

6)去掉重複的行:distinct

select  distinct 專業名 from xs;

對查詢結果排序

order by 子句:

升序:asc  (默認)

降序:desc

如果是按多個字段排序,先按第一個字段排,當第一個字段的值相同時,在按第二個排。

4 limit子句:限制結果集中的行數

一般limit子句放在select語句的最後

limit 5   :表示返回結果集的前面5條記錄

limit 3,5:表示返回從第4行開始的5條記錄

分組:分類彙總

聚合函數:

count(*):統計記錄的條數  

count(字段名):統計字段中有值的記錄個數。(不考慮null

count(distinct 字段名): 去掉重複值後在計算有值的個數

max(字段名):計算某一列最大值

min(字段名):計算某一列最小值

sum(字段名):求和

avg(字段名):求平均值

統計xs表中的記錄數:select count(*) from xs

查詢選修了課程的學生人數

select count(distinct 學號) as 人數 from xs_kc;

查詢選修101課程的學生的最高分

select max(成績) as 最高分 from xs_kc

where 課程號=101;

分組:group by 字段名:

根據字段的值對記錄進行分組

group  by 性別

select 性別,count(*) as 人數 from xs

group by 性別;

分組後可以看哪些字段:一般是分組的字段,和使用聚合函數的列。

group by 字段名1,字段名2

select 專業名,性別,count(*) as 人數

from xs

group by 專業名,性別

with rollup;

查詢平均分是大於77的課程號,和相應的平均分。

select 課程號,avg(成績) as 平均分

from xs_kc

group by 課程號

having avg(成績)>77;

使用分組後在進行挑選   having關鍵字

having where的區別:where是對原始記錄進行挑選,跟在from後。

having:對分組後的記錄進行挑選,跟在group by 後。

select 學號  from xs_kc

where 成績>=80

group by 學號

having count(*)>2

查詢每個學生的學號和選課數

select 學號,count(*) as 選課數

from xs_kc

group by 學號;

查詢選修了2門課程以上的學生學號。

select 學號

from xs_kc

group by 學號

having count(*)>2;

查詢每門課程號及其選課人數。

select  課程號,count(*) as 人數

from test_sc

group by 課程號;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章