詳解MySQL中的分組查詢與串連查詢語句_Mysql

來源:互聯網
上載者:User

分組查詢 group by
group by 屬性名稱 [having 條件運算式][ with rollup]
“屬性名稱 ”指按照該欄位值進行分組;“having 條件運算式 ”用來限制分組後的顯示,滿足條件的結果將被顯示;with rollup 將會在所有記錄的最後加上一條記錄,該記錄是上面所有記錄的總和。

1)單獨使用
group by 單獨使用,查詢結果只顯示一個分組的一條記錄。
執行個體:

select * from employee group by sex;

將只顯示男女兩條記錄。

2)與group_concat()函數一起使用
每個分組中指定欄位值都顯示出來
執行個體:

select sex,group_concat(name) from employee group by sex;

顯示結果中“女”會顯示所有sex為“女”的名字name

sex | group_concat(name)女 | 小紅,小蘭男 | 張三,王五,王六

3)與集合函數一起使用
執行個體:

select sex,count(sex) from employee group by sex;

結果:

sex | count(num)女 | 1男 | 3

count()為計算個數的方法。

4)與having一起使用
“having條件運算式”,可以限制輸出結果。只有滿足條件運算式的結果才顯示。
執行個體:

select sex,count(sex) from employee group by sex having count(sex) >= 3;

結果:

sex | count(sex)男 | 3

“having條件運算式”作用於分組後的記錄。

5)按多欄位進行分組

select * from employee group by d_id,sex;

查詢結果先按d_id分組,再按sex進行分組

6) 與with rollup一起使用
使用with rollup將會在所有記錄的最後加上一條記錄,這條記錄是上面所有記錄的總和
執行個體:

select sex,count(sex) from employee group by sex with rollup;

結果:

sex | count(sex)女 | 1男 | 5null | 6

如果是字串的話,比如姓名就會產生“張三,李四,王五”這種類型的結果,即name總和。

串連查詢
將兩個及兩個以上的表串連起來選取所需資料。

1)內串連查詢:
當兩個表中具有相同意義的欄位值相等時,就查詢出該條記錄。
執行個體:

複製代碼 代碼如下:

select num,name,employee.d_id,age,d_name from employee,department where employee.d_id = department.d_id

因欄位名相同,所以取d_id欄位值時最好指定哪張表的欄位。

2)外串連查詢
select 屬性名稱列表 from 表名1 left|right join 表名2 on 表名1.屬性名稱1=表名2.屬性名稱2;
左串連查詢:
進行左串連查詢時,可以查出表名1中所指的表中所有記錄。而表名2所指表中,只能查詢出匹配的記錄。
執行個體:

複製代碼 代碼如下:

select num,name,employee.d_id,age,d_name from employee left join department on employee.d_id = department.d_id;

右串連查詢:
與左串連相反,可以查詢出表名2中的的所有記錄,而表名1中所指的表中,只查詢出匹配的記錄。


PS:使用集合函數查詢
集合函數包括count(),sum(),avg(),max()和min()。
1)count()函數
統計記錄條數
執行個體:

select count(*) from employee;

與group by一起使用

select d_id,count(*) from employee group by d_id;

上述語句會先分組後統計。

2) sum()函數
sum()函數是求和函數
執行個體:

select num,sum(score) from grade where num= 1001;select num,sum(score) from grade group by num;

sum()只能計算數實值型別欄位。
3)avg()函數
avg()函數是求平均值函數。
執行個體:

select avg(age) from employee;select course,avg(score) from group by course;

4)max(),min()函數
求最大值和最小值。
執行個體:
select max(age) from employee;
select num,course,max(score) from grade group by course;
對於字串的最大值問題,max()函數是使用字元對應的ascii碼進行計算的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.