樣板,空值(null)自改mysql
create database sky;sql
use sky;ide
create table m1(spa
id int(11),it
name char(20),table
age tinyint(10),class
sex enum('男','女'),select
score tinyint(10),im
address char(20)統計
) default charset=utf8;
insert into m1 values
(1,'L1',21,'男',90,'北京'),
(2,'L2',19,'男',91,'上海'),
(3,'L3',24,'女',95,'廣州'),
(4,'L4',22,'男',89,'廣州'),
(5,'L5',20,'女',86,'上海'),
(6,'L6',19,'女',99,'廣州');
分類
1. avg(字段名):字段的平均值
2. sum(字段名): 字段的和
3. max(字段名): 求字段的最大值
4. min(字段名) ; 求字段的最小值
5. count(字段名): 統計該字段有記錄的個數
例如:
mysql> select * from m1;
+------+------+------+------+-------+---------+
| id | name | age | sex | score | address |
+------+------+------+------+-------+---------+
| 2 | L2 | NULL | 男 | 91 | 上海 |
| 3 | L3 | 24 | 女 | 95 | 廣州 |
| 4 | L4 | 22 | 男 | 101 | 廣州 |
| 5 | L5 | NULL | 女 | 86 | 上海 |
| 6 | L6 | 19 | 女 | 99 | 北京 |
| 1 | L1 | 21 | 男 | 90 | 北京 |
+------+------+------+------+-------+---------+
6 rows in set (0.00 sec)
顯示score字段最高的
mysql> select max(score) as SCORE from m1; # as 別名
+-------+
| SCORE |
+-------+
| 101 |
+-------+
1 row in set (0.00 sec)
統計字段有幾行,as 別名
mysql> select count(name) as N,count(age) as A from m1;
+---+---+
| N | A |
+---+---+
| 6 | 4 |
+---+---+
1 row in set (0.02 sec)
計算總分
mysql> select sum(score) as score from m1;
+-------+
| score |
+-------+
| 562 |
+-------+
1 row in set (0.01 sec)
計算每一個城市的平局分數
mysql> select address,avg(score) from m1 group by address;
+---------+------------+
| address | avg(score) |
+---------+------------+
| 上海 | 88.5000 |
| 北京 | 94.5000 |
| 廣州 | 98.0000 |
+---------+------------+
3 rows in set (0.00 sec)
查看那兩個國家人最多,顯示前兩名
mysql> select address,count(name) as name_count from m1
-> group by address
-> order by name_count desc
-> limit 2;
+---------+------------+
| address | name_count |
+---------+------------+
| 廣州 | 3 |
| 上海 | 2 |
+---------+------------+
2 rows in set (0.00 sec)
distinct
做用:去重
distinct 處理的是存在的字段名
有多少個城市
mysql> select distinct address from m1;
+---------+
| address |
+---------+
| 北京 |
| 上海 |
| 廣州 |
+---------+
3 rows in set (0.00 sec)