1. 程式人生 > >MySQL中的分組查詢與連線查詢語句

MySQL中的分組查詢與連線查詢語句

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

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

?
1 select * from employee group by sex;

將只顯示男女兩條記錄。

2)與group_concat()函式一起使用
每個分組中指定欄位值都顯示出來
例項:

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

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

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

3)與集合函式一起使用
例項:

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

結果:

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

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

4)與having一起使用
“having條件表示式”,可以限制輸出結果。只有滿足條件表示式的結果才顯示。
例項:

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

結果:

?
1 2 sex | count(sex) 男 | 3

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

5)按多欄位進行分組

?
1 select * from employee group by d_id,sex;

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

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

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

結果:

?
1 2 3 4 sex | count(sex) 女 | 1 男 | 5 null | 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()函式
統計記錄條數
例項:

?
1 select count (*) from employee;

與group by一起使用

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

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

2) sum()函式
sum()函式是求和函式
例項:

?
1 2 3 select num, sum (score) from grade where num= 1001;   select num, sum (score) from grade group by num;

sum()只能計算數值型別欄位。
3)avg()函式
avg()函式是求平均值函式。
例項:

?
1 2 3 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碼進行計算的。

原文連結:http://www.jb51.net/article/81479.htm