count函數的用處在與統計數目,在實際的應用中,這個函數的用處是非常大的。
現在創建一張pet表和owner表,分別代表寵物和它們的主人。
create table pet(id int(11) primary key auto_increment, name char(20), species char(20), owner_id int(11), constraint pet_ibfk_01 foreign key owner_id references owner (id))engine=innodb default charset=gbk;
create table owner(id int(11) primary key auto_increment, name char(20))engine=innodb default charset=gbk;
現在表owner中記錄如下
id | name |
1 | zhangsan |
2 | lisi |
表pet中記錄如下
id | name | species | owner_id |
1 | lili | cat | 1 |
2 | haha | dog | 2 |
3 | miaomiao | cat | 1 |
select count(*) from pet;
輸出如下
count(*) |
3 |
2.使用count來統計不同種類的寵物
select species, count(species) from pet group by species;
輸出如下:
species | count(species) |
cat | 2 |
dog | 1 |
再深入地查詢每名主人有着幾隻寵物
select owner.name, count(owner_id) from pet left join owner on owner_id=owner.id group by owner_id;
輸出如下:
name | count(owner_id) |
zhangsan | 2 |
lisi | 1 |
3.count(col_name)統計一個列
單獨的使用count(col_name)只會輸出該列中非null的列值數目。
species | count(species) |
cat | 2 |
dog | 1 |