mysql程序分客户端和服务器端两种:
客户端
服务器端
mysql工具用法:
语法:mysql [OPTIONS] [databases]
常用的OPTIONS:
-uUSERNAME 指定用户名,默认为root
-hHOST 指定服务器主机,默认为localhost
-pPASSWORD 指定用户的密码
-P# 指定数据监听的端口,#需用实际的端口号代替
-V 查看当前使用的mysql版本
-e 不登录mysql执行sql语句后退出
登录mysql:mysql -uroot -p123456 -h127.0.0.1
服务器监听的两种socket地址:
DDL操作包括定义数据库、表、列。create 创建
,show 查看
,drop 删除
mysql> create database if not exists abc;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| abc |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.09 sec)
mysql> show create database sys;
+----------+--------------------------------------------------------------+
| Database | Create Database |
+----------+--------------------------------------------------------------+
| sys | CREATE DATABASE `sys` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+--------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> show create databases abc;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'databases abc' at line 1
mysql> show create database abc;
+----------+----------------------------------------------------------------+
| Database | Create Database |
+----------+----------------------------------------------------------------+
| abc | CREATE DATABASE `abc` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+----------------------------------------------------------------+
1 row in set (0.01 sec)
mysql> drop database if exists abc;
Query OK, 0 rows affected (0.05 sec)
mysql> use sys;
Database changed
格式:create table 表名(字段名 类型 修饰符,字段名 类型 修饰符)
例:
mysql> use abc
Database changed
mysql> create table ggg(id int NOT NULL,name VARCHAR(100) NOT NULL,age tinyint);
Query OK, 0 rows affected (0.00 sec)
mysql> show tables;
+---------------+
| Tables_in_abc |
+---------------+
| ggg |
+---------------+
1 row in set (0.00 sec)
mysql> create table abc(id int primary key auto_increment not null,name varchar(50) not null,age tinyint);
Query OK, 0 rows affected (0.03 sec)
//设定了主键约束的列,列中的字段只能出现一次。且必须提供数据,不能为空
//int为整数类型,primary key为主键,auto_increment为自动递增,not null表示不能为空,varchar为字符串类型,tinyint整数类型,值为0-255
mysql> desc abc;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
mysql> desc ggg;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | varchar(100) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> show create table ggg;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------+
| ggg | CREATE TABLE `ggg` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`age` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> drop table if exists ggg;
Query OK, 0 rows affected (0.01 sec)
语法:alter TABLE 表名 DROP 列名;
mysql> alter table ggg drop age;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc ggg;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> rename table ggg to heihei;
Query OK, 0 rows affected (0.00 sec)
mysql> show tables;
+---------------+
| Tables_in_abc |
+---------------+
| heihei |
+---------------+
1 row in set (0.00 sec)
语法:alter TABLE 表名 CHANGE 列名 新列名 列类型;
mysql> alter table heihei change id num int;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc heihei;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| num | int(11) | YES | | NULL | |
| name | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
语法:alter TABLE 表名 CHARACTER SET 字符集
mysql> alter table abc character set utf8;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE abc;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| abc | CREATE TABLE `abc` (
`id` int(11) DEFAULT NULL,
`name` varchar(100) CHARACTER SET latin1 DEFAULT NULL,
`age` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
语法:alter table 表名 add 列名 列类型;
mysql> alter table heihei add age tinyint;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc heihei;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| num | int(11) | YES | | NULL | |
| name | varchar(100) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql用户账号由两部分组成(‘USERNAME’@‘HOST’),HOST用于限制此用户可以通过哪些主机远程连接,其值为:
- IP地址,如192.168.1.1
- 通配符,
%
匹配任意长度的任意字符,_
匹配任意单个字符
语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
mysql> create user 'tom'@'127.0.0.1' identified by '123456';
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements //错误1819 (HY000):您的密码不满足当前策略要求
mysql> show variables like "%validate%"; //查看策略
+--------------------------------------+--------+
| Variable_name | Value |
+--------------------------------------+--------+
| query_cache_wlock_invalidate | OFF |
| validate_password_check_user_name | OFF |
| validate_password_dictionary_file | |
| validate_password_length | 8 | //这里设置密码最小长度为6
| validate_password_mixed_case_count | 1 |
| validate_password_number_count | 1 |
| validate_password_policy | MEDIUM | //这里设置为0,就可以接受简单密码了
| validate_password_special_char_count | 1 |
+--------------------------------------+--------+
8 rows in set (0.01 sec)
mysql> set global validate_password_length=6;
Query OK, 0 rows affected (0.00 sec)
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.00 sec)
//再次创建用户
mysql> create user 'tom'@'127.0.0.1' identified by '123456';
Query OK, 0 rows affected (0.31 sec)
//登录
[root@node3 ~]# mysql -utom -p123456 -h127.0.0.1
...
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
语法:DROP USER 'username'@'host';
mysql> drop user 'tom'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)
用户信息存放在mysql库中的user表中
mysql> use mysql;
Database changed
mysql> select * from user\G
*************************** 1. row ***************************
Host: localhost
User: root
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
......
......
mysql> show character set;
+----------+---------------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+---------------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
...
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment | Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES | YES | YES |
| MRG_MYISAM | YES | Collection of identical MyISAM tables | NO | NO | NO |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| MyISAM | YES | MyISAM storage engine | NO | NO | NO |
| CSV | YES | CSV storage engine | NO | NO | NO |
| ARCHIVE | YES | Archive storage engine | NO | NO | NO |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)
mysql> show tables from abc;
+---------------+
| Tables_in_abc |
+---------------+
| heihei |
+---------------+
1 row in set (0.00 sec)
语法:SHOW TABLE STATUS LIKE 'table_name'\G
mysql> use abc; //进入数据库abc
Database changed
mysql> show table status like 'heihei'\G //查看表heihei的状态
*************************** 1. row ***************************
Name: heihei
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2020-05-20 09:39:20
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
语法:HELP keyword;
mysql> help create database; //获取创建数据库的帮助
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.
URL: https://dev.mysql.com/doc/refman/5.7/en/create-database.html
mysql> help create table; //获取创建表的帮助
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
......
DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT)
INSERT用来进行插入操作
语法:INSERT INTO 表名(列名1,列名2 ...)VALUES(列值1,列值2...);
mysql> insert into info value(1,'tom',20),(2,'jerry',25),(3,'zhangshan',30);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from info;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 25 |
| 3 | zhangshan | 30 |
+------+-----------+------+
3 rows in set (0.00 sec)
mysql> insert into info(name) value('lisi');
Query OK, 1 row affected (0.00 sec)
mysql> select * from info;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 25 |
| 3 | zhangshan | 30 |
| NULL | lisi | NULL |
+------+-----------+------+
4 rows in set (0.00 sec)
SELECT用来进行查找操作
语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
column值
*
表示所有字段as
字段别名,临时修改字段名示例:
mysql> select * from info;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 25 |
| 3 | zhangshan | 30 |
| NULL | lisi | NULL |
+------+-----------+------+
4 rows in set (0.00 sec)
mysql> select name from info;
+-----------+
| name |
+-----------+
| tom |
| jerry |
| zhangshan |
| lisi |
+-----------+
4 rows in set (0.00 sec)
mysql> select id as 编号 from info;
+--------+
| 编号 |
+--------+
| 1 |
| 2 |
| 3 |
| NULL |
+--------+
4 rows in set (0.00 sec)
条件判断WHERE
示例:
mysql> select * from info where age >= 25;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 2 | jerry | 25 |
| 3 | zhangshan | 30 |
+------+-----------+------+
2 rows in set (0.30 sec)
mysql> select * from info where age between 20 and 25;
+------+-------+------+
| id | name | age |
+------+-------+------+
| 1 | tom | 20 |
| 2 | jerry | 25 |
+------+-------+------+
2 rows in set (0.00 sec)
mysql> select * from info where age like '3%'; //%表示匹配任意单个字符任意次,_表示匹配任意单个字符一次
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 3 | zhangshan | 30 |
+------+-----------+------+
1 row in set (0.00 sec)
mysql> select * from info where name rlike '^t';
+------+------+------+
| id | name | age |
+------+------+------+
| 1 | tom | 20 |
+------+------+------+
1 row in set (0.00 sec)
mysql> select * from info where id is null;
+------+------+------+
| id | name | age |
+------+------+------+
| NULL | lisi | NULL |
+------+------+------+
1 row in set (0.00 sec)
mysql> select * from info where id is not null;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 25 |
| 3 | zhangshan | 30 |
+------+-----------+------+
3 rows in set (0.00 sec)
mysql> select * from info where age < 26 and name like 't%';
+------+------+------+
| id | name | age |
+------+------+------+
| 1 | tom | 20 |
+------+------+------+
1 row in set (0.00 sec)
mysql> select * from info where age = 20 or age = 30;
+------+-----------+------+
| id | name | age |
+------+-----------+------+
| 1 | tom | 20 |
| 3 | zhangshan | 30 |
+------+-----------+------+
2 rows in set (0.00 sec)
排序语句ORDER BY(默认为升序ASC,逆序为DESC)
用法:
示例:
mysql> select * from student order by age;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 7 | lisi | NULL |
| 9 | wangwu | 3 |
| 8 | chengshuo | 10 |
| 10 | qiuyi | 15 |
| 1 | tom | 20 |
| 6 | zhangshan | 20 |
| 11 | qiuxiaotian | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 5 | zhangshan | 26 |
| 4 | sean | 28 |
+----+-------------+------+
11 rows in set (0.00 sec)
mysql> select * from student order by age desc;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 3 | wangqing | 25 |
| 2 | jerry | 23 |
| 1 | tom | 20 |
| 6 | zhangshan | 20 |
| 11 | qiuxiaotian | 20 |
| 10 | qiuyi | 15 |
| 8 | chengshuo | 10 |
| 9 | wangwu | 3 |
| 7 | lisi | NULL |
+----+-------------+------+
11 rows in set (0.00 sec)
mysql> select * from student order by id limit 3;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
+----+----------+------+
3 rows in set (0.00 sec)
mysql> select * from student order by id desc limit 2,4;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 9 | wangwu | 3 |
| 8 | chengshuo | 10 |
| 7 | lisi | NULL |
| 6 | zhangshan | 20 |
+----+-----------+------+
4 rows in set (0.00 sec)
update用来对表进行更新修改
语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
示例:
mysql> select * from student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisi | NULL |
| 8 | chengshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
mysql> update student set age = 18 where name = 'tom';
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from student where name = 'tom';
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | tom | 18 |
+----+------+------+
1 row in set (0.00 sec)
mysql> update student set name = 'lisa',age = 24 where name = 'lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from student where name = 'lisa';
+----+------+------+
| id | name | age |
+----+------+------+
| 7 | lisa | 24 |
+----+------+------+
1 row in set (0.00 sec)
delete用来删除表中的内容
语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
示例:
mysql> delete from student where id = 11;
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 18 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisa | 24 |
| 8 | chengshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
+----+-----------+------+
10 rows in set (0.00 sec)
mysql> delete from student;
Query OK, 10 rows affected (0.01 sec)
mysql> select * from student;
Empty set (0.00 sec)
mysql> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
truncate也是用来删除数据
语法:TRUNCATE table_name;
truncate与delete的区别:
示例:
mysql> select * from student;
+----+-------+------+
| id | name | age |
+----+-------+------+
| 12 | tom | 12 |
| 13 | jerry | 20 |
+----+-------+------+
2 rows in set (0.00 sec)
mysql> truncate student;
Query OK, 0 rows affected (0.03 sec)
mysql> select * from student;
Empty set (0.00 sec)
mysql> insert student(name,age) values('tom',40),('jerry',30);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from student;
+----+-------+------+
| id | name | age |
+----+-------+------+
| 1 | tom | 40 |
| 2 | jerry | 30 |
+----+-------+------+
2 rows in set (0.00 sec)
DCL操作包括创建授权grant
、查看授权show grants
、取消授权revoke
语法:GRANT priv_type,... ON [object_type] db_name.table_name TO ‘username'@'host' [IDENTIFIED BY 'password'] [WITH GRANT OPTION];
WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,说白点就是将自己的权限完全复制给另一个用户。
权限类型:
操作对象:
示例:
mysql> grant all on *.* to 'tom'@'localhost' identified by 'aAbis123!';
Query OK, 0 rows affected, 1 warning (0.03 sec)
mysql> flush privileges; //刷新权限
mysql> grant select on yy123.student to 'jerrt'@'192.168.207.130' identified by 'ddDD123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> flush privileges; //刷新权限
语法:SHOW GRANTS [FOR 'USERNAME'@'IP']
示例:
mysql> show grants;
+---------------------------------------------------------------------+
| Grants for root@localhost |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)
mysql> show grants for 'tom'@'localhost';
+--------------------------------------------------+
| Grants for tom@localhost |
+--------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'tom'@'localhost' |
+--------------------------------------------------+
1 row in set (0.00 sec)
语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';
示例:
mysql> revoke all on *.* from 'tom'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges; //刷新权限
Query OK, 0 rows affected (0.00 sec)
Group By,group即组,根据by指定的规则对数据进行分组,所谓的分组就是将一个“数据集”划分成若干个“小区域”,然后针对若干个“小区域”进行数据处理
将a、b、c进行汇总求和
mysql> select * from test;
+------+------+------+
| id | num | info |
+------+------+------+
| a | 5 | NULL |
| a | 2 | NULL |
| b | 10 | NULL |
| b | 6 | NULL |
| b | 3 | NULL |
| c | 9 | NULL |
| c | 9 | NULL |
| c | 8 | NULL |
| c | 7 | NULL |
| c | 4 | NULL |
| a | 11 | NULL |
+------+------+------+
11 rows in set (0.00 sec)
mysql> select id,sum(num) as total from test group by
id;
+------+-------+
| id | total |
+------+-------+
| a | 18 |
| b | 19 |
| c | 37 |
+------+-------+
3 rows in set (0.00 sec)
将a、b、c进行汇总求和并降序排序
mysql> select id,sum(num) as total from test group by id order by sum(num) desc;
+------+-------+
| id | total |
+------+-------+
| c | 37 |
| b | 19 |
| a | 18 |
+------+-------+
3 rows in set (0.00 sec)
group by语句中select指定的字段必须是“分组依据字段”,其他字段若想出现在select中则必须包含在聚合函数中,常见的聚合函数如下表:
函数 | 作用 |
---|---|
sum | 求和 |
max | 最大值 |
min | 最小值 |
avg | 平均值 |
first | 第一条记录 |
last | 最后一条记录 |
count | 统计记录数 |
示例:
mysql> select id,avg(num) as 平均值 from test group by id;
+------+-----------+
| id | 平均值 |
+------+-----------+
| a | 6.0000 |
| b | 6.3333 |
| c | 7.4000 |
+------+-----------+
3 rows in set (0.00 sec)
mysql> select id,count(*) as 记录次数 from test group byy id;
+------+-----------+
| id | 记录次数 |
+------+-----------+
| a | 3 |
| b | 3 |
| c | 5 |
+------+-----------+
3 rows in set (0.00 sec)
示例:
mysql> select id,sum(num) as 数量和 from test group by id having sum(num) > 18;
+------+-----------+
| id | 数量和 |
+------+-----------+
| b | 19 |
| c | 37 |
+------+-----------+
2 rows in set (0.00 sec)
Having与Where联合使用方法
//先过滤num大于8的,然后进行分组,分组后再过滤和大于10的
mysql> select id,sum(num) from test where num > 8 grouup by id having sum(num) > 10;
+------+----------+
| id | sum(num) |
+------+----------+
| a | 11 |
| c | 18 |
+------+----------+
2 rows in set (0.00 sec)
需求:
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| scores | tinyint(4) | YES | | NULL | |
+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 1 | tom | 80 |
| 2 | jerry | 60 |
| 3 | zhangshan | 59 |
| 4 | zhangshan | 85 |
| 5 | lisi | 70 |
| 6 | wangwu | 66 |
| 7 | yuchuan | 100 |
| 8 | qiqi | NULL |
| 9 | gege | 10 |
+----+-----------+--------+
解决需求:
1.创建一个数据库yuchuan,并创建一张表transcript,该表包含三个字段(id,name,scores)
mysql> create database yuchuan;
Query OK, 1 row affected (0.00 sec)
mysql> use yuchuan;
Database changed
mysql> create table transcript(id int primary key auto_increment not null,name varchar(50) not null,scores tinyint);
Query OK, 0 rows affected (0.00 sec)
mysql> desc transcript;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| scores | tinyint(4) | YES | | NULL | |
+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
2.往新建的transcript表中插入数据(用insert语句)
mysql> insert transcript(name,scores) values('tom',80),('jerry',60),('zhangshan',59),('zhangshan',85),('lisi',70),('wangwu',66),('yuchuuan',100),('qiqi',null),('gege',10);
Query OK, 9 rows affected (0.00 sec)
Records: 9 Duplicates: 0 Warnings: 0
mysql> select * from transcript;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 1 | tom | 80 |
| 2 | jerry | 60 |
| 3 | zhangshan | 59 |
| 4 | zhangshan | 85 |
| 5 | lisi | 70 |
| 6 | wangwu | 66 |
| 7 | yuchuan | 100 |
| 8 | qiqi | NULL |
| 9 | gege | 10 |
+----+-----------+--------+
9 rows in set (0.00 sec)
3.修改lisi的成绩为50
mysql> update transcript set scores = 50 where name = 'lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from transcript where name = 'lisi';
+----+------+--------+
| id | name | scores |
+----+------+--------+
| 5 | lisi | 50 |
+----+------+--------+
1 row in set (0.00 sec)
4.以scores字段降序排序
mysql> select * from transcript order by scores desc;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 7 | yuchuan | 100 |
| 4 | zhangshan | 85 |
| 1 | tom | 80 |
| 6 | wangwu | 66 |
| 2 | jerry | 60 |
| 3 | zhangshan | 59 |
| 5 | lisi | 50 |
| 9 | gege | 10 |
| 8 | qiqi | NULL |
+----+-----------+--------+
9 rows in set (0.00 sec)
5.查询表中成绩最低的3位同学跳过前2位
mysql> select * from transcript order by scores limit 2,3;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 5 | lisi | 50 |
| 3 | zhangshan | 59 |
| 2 | jerry | 60 |
+----+-----------+--------+
3 rows in set (0.00 sec)
6.查询表中成绩最高的4位同学
mysql> select * from transcript order by scores desc limit 4;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 7 | yuchuan | 100 |
| 4 | zhangshan | 85 |
| 1 | tom | 80 |
| 6 | wangwu | 66 |
+----+-----------+--------+
4 rows in set (0.00 sec)
7.查询表中名字叫zhangshan的记录
mysql> select * from transcript where name = 'zhangshan';
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 3 | zhangshan | 59 |
| 4 | zhangshan | 85 |
+----+-----------+--------+
2 rows in set (0.00 sec)
8.查询表中名字叫zhangshan且成绩大于60分的记录
mysql> select * from transcript where name = 'zhangshan' and scores > 60;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 4 | zhangshan | 85 |
+----+-----------+--------+
1 row in set (0.00 sec)
9.查询表中成绩在60-100分之间的记录
mysql> select * from transcript where scores between 60 and 100;
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 1 | tom | 80 |
| 2 | jerry | 60 |
| 4 | zhangshan | 85 |
| 6 | wangwu | 66 |
| 7 | yuchuan | 100 |
+----+-----------+--------+
5 rows in set (0.00 sec)
10.修改wangwu的成绩为90
mysql> update transcript set scores = 90 where name = 'wangwu';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from transcript where name = 'wangwu';
+----+--------+--------+
| id | name | scores |
+----+--------+--------+
| 6 | wangwu | 90 |
+----+--------+--------+
1 row in set (0.00 sec)
11.删除表中名字叫zhangshan且成绩小于60的记录
mysql> delete from transcript where name = 'zhangshan'' and scores < 60;
Query OK, 1 row affected (0.00 sec)
mysql> select * from transcript where name = 'zhangshan';
+----+-----------+--------+
| id | name | scores |
+----+-----------+--------+
| 4 | zhangshan | 85 |
+----+-----------+--------+
1 row in set (0.00 sec)