MySQL基本用法

MySQL

  • 1. MySQL的程序组成
  • 2. MySQL数据库操作
    • 2.1 DLL操作
      • 2.1.1 数据库操作
      • 2.1.2 表操作
      • 2.1.3 用户操作
      • 2.1.4 查看命令show
      • 2.1.5 获取帮助
    • 2.2 DML操作
      • 2.2.1 INSERT语句
      • 2.2.2 SELECT语句
      • 2.2.3 update语句
      • 2.2.4 delete语句
      • 2.2.5 truncate语句
    • 2.3 DCL操作
      • 2.3.1 创建授权grant
      • 2.3.2 查看授权
      • 2.3.3 取消授权REVOKE
    • 2.4 Group By用法
      • 2.4.1 简单求和Group By
      • 2.4.2 Group By和Order By
      • 2.4.3 Group By与聚合函数
      • 2.4.4 Having与Where的区别
  • 3.实例


1. MySQL的程序组成


mysql程序分客户端和服务器端两种:

  • 客户端

    • mysql:CLI交互式客户端程序
    • mysql_secure_installation:安全初始化
    • mysqldump:mysql备份工具
    • mysqladmin:执行管理操作,可以用来检查服务器的配置和当前状态、创建和删除数据库等
  • 服务器端

    • mysqld:通过开启此程序,开启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地址:

  • ip socket 默认监听在tcp3306端口,支持远程通信
  • unix sock 监听在sock文件(/tmp/mysql.sock,/var/lib/mysql/mysql.sock)上,仅支持本地通信,server地址只能为localhost,127.0.01

2. MySQL数据库操作


2.1 DLL操作

DDL操作包括定义数据库、表、列。create 创建show 查看drop 删除

2.1.1 数据库操作

  • 创建数据库
mysql> create database if not exists abc;
Query OK, 1 row affected (0.00 sec)
  • 查看MySQL服务器中有哪些数据库
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

2.1.2 表操作

  • 创建表
格式: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)

2.1.3 用户操作

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
......
......

2.1.4 查看命令show

  • 查看支持的所有字符集
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)

2.1.5 获取帮助

语法: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]
......

2.2 DML操作

DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT)

2.2.1 INSERT语句

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)

2.2.2 SELECT语句

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)
  • 查找name字段
mysql> select name from info;
+-----------+
| name      |
+-----------+
| tom       |
| jerry     |
| zhangshan |
| lisi      |
+-----------+
4 rows in set (0.00 sec)
  • 将id字段使用别名代替
mysql> select id as 编号 from info;
+--------+
| 编号   |
+--------+
|      1 |
|      2 |
|      3 |
|   NULL |
+--------+
4 rows in set (0.00 sec)

条件判断WHERE

  • 操作符
    • >,<,>=,<=,=,!=
    • BETWEEN column# AND column#
    • LIKE:模糊匹配
    • RLIKE:基于正则表达式进行模式匹配
    • IS NOT NULL:非空
    • IS NULL:空
  • 条件逻辑操作
    • AND 并且
    • OR 或者
    • NOT 非

示例:

  • 查找年龄大于等于25的
mysql> select * from info where age >= 25;
+------+-----------+------+
| id   | name      | age  |
+------+-----------+------+
|    2 | jerry     |   25 |
|    3 | zhangshan |   30 |
+------+-----------+------+
2 rows in set (0.30 sec)
  • 查找年龄在20到25之间的(包括20和25)
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)
  • 查看年龄3开头的
mysql> select * from info where age like '3%';  //%表示匹配任意单个字符任意次,_表示匹配任意单个字符一次
+------+-----------+------+
| id   | name      | age  |
+------+-----------+------+
|    3 | zhangshan |   30 |
+------+-----------+------+
1 row in set (0.00 sec)
  • 使用正则表达式匹配名字以t开头的
mysql> select * from info where name rlike '^t';
+------+------+------+
| id   | name | age  |
+------+------+------+
|    1 | tom  |   20 |
+------+------+------+
1 row in set (0.00 sec)
  • 查找id为空的
mysql> select * from info where id is null;
+------+------+------+
| id   | name | age  |
+------+------+------+
| NULL | lisi | NULL |
+------+------+------+
1 row in set (0.00 sec)
  • 查找id非空的
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)
  • 查找年龄小于26,并且叫名字以t开头的
mysql> select * from info where age < 26 and name like 't%';
+------+------+------+
| id   | name | age  |
+------+------+------+
|    1 | tom  |   20 |
+------+------+------+
1 row in set (0.00 sec)
  • 查找年龄为20或者30的
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)

用法:

  • ORDER BY ‘column_name’ 根据column_name进行升序排序
  • ORDER BY ‘column_name’ DESC 根据column_name进行降序排序
  • ORDER BY ‘column_name’ LIMIT 2 根据coulumn_name进行升序排序,并取出前两个结果
  • ORDER BY ‘column_name’ LIMIT 1,2 根据coulumn_name进行升序排序,并跳过第一个结果,从第二个开始取出两个结果

示例:

  • 根据年龄进行升序排序
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)
  • 根据id进行升序排序,并取出前3个结果
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)
  • 根据id进行降序排序,并跳过前两个结果,取出从第3个开始的4个结果
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)

2.2.3 update语句

update用来对表进行更新修改
语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

示例:

  • 修改student表中name为tom的age为18
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)
  • 修改student表中name为lisi的,修改name为lisa,age为24
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)

2.2.4 delete语句

delete用来删除表中的内容
语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

示例:

  • 删除student表中id为11的一行数据
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)

2.2.5 truncate语句

truncate也是用来删除数据
语法:TRUNCATE table_name;

truncate与delete的区别:

  • truncate不能删除单条数据,只能删除全部数据
  • truncate删除的数据在没有备份的情况下无法恢复。而delete删除数据会生成日志可以通过回滚日志恢复数据
  • truncate删除数据后,设定了自动递增的列,计数会从初始值开始。
  • 对于有外键约束引用、加入了索引视图的表,不能使用truncate删除数据

示例:

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)

2.3 DCL操作

DCL操作包括创建授权grant、查看授权show grants、取消授权revoke

2.3.1 创建授权grant

语法:GRANT priv_type,... ON [object_type] db_name.table_name TO ‘username'@'host' [IDENTIFIED BY 'password'] [WITH GRANT OPTION];

WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,说白点就是将自己的权限完全复制给另一个用户。

权限类型:

  • ALL 所有权限
  • SELECT 读取内容的权限
  • INSERT 插入内容的权限
  • UPDATE 更新内容的权限
  • DELETE 删除内容的权限

操作对象:

  • *.* 所有库的所有表
  • db_name 指定库的所有表
  • db_name.table_name 指定库的指定表

示例:

  • 授权tom用户在本机上登录访问所有数据库和表,并拥有所有权限
mysql> grant all on *.* to 'tom'@'localhost' identified by 'aAbis123!';
Query OK, 0 rows affected, 1 warning (0.03 sec)

mysql> flush privileges;  //刷新权限
  • 授权jerrt用户在192.168.207.130上远程登录访问yy123数据库的student表,并只有看的权限
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;  //刷新权限

2.3.2 查看授权

语法: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)

2.3.3 取消授权REVOKE

语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';

示例:

  • 取消tom用户,所有库中的所有表的所有权限
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)

2.4 Group By用法

Group By,group即组,根据by指定的规则对数据进行分组,所谓的分组就是将一个“数据集”划分成若干个“小区域”,然后针对若干个“小区域”进行数据处理

2.4.1 简单求和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)

2.4.2 Group By和Order By

将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)

2.4.3 Group By与聚合函数

group by语句中select指定的字段必须是“分组依据字段”,其他字段若想出现在select中则必须包含在聚合函数中,常见的聚合函数如下表:

函数 作用
sum 求和
max 最大值
min 最小值
avg 平均值
first 第一条记录
last 最后一条记录
count 统计记录数

示例:

  • 求各id平均值
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)
  • 求各id记录次数
mysql> select id,count(*) as 记录次数 from test group byy id;
+------+-----------+
| id   | 记录次数    |
+------+-----------+
| a    |         3 |
| b    |         3 |
| c    |         5 |
+------+-----------+
3 rows in set (0.00 sec)

2.4.4 Having与Where的区别

  • where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,where条件中不能包含聚组函数,使用where条件过滤出特定的行。
  • having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件过滤出特定的组,也可以使用多个分组标准进行分组。

示例:

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)

3.实例


需求:

  • 创建一个数据库yuchuan,并创建一张表transcript,该表包含三个字段(id,name,scores),表结构如下:
+--------+-------------+------+-----+---------+----------------+
| 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)
  • 往新建的transcript表中插入数据(用insert语句),结果应如下所示:
+----+-----------+--------+
| 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 |
+----+-----------+--------+
  • 修改lisi的成绩为50
  • 以scores字段降序排序
  • 查询表中成绩最低的3位同学跳过前2位
  • 查询表中成绩最高的4位同学
  • 查询表中名字叫zhangshan的记录
  • 查询表中名字叫zhangshan且成绩大于60分的记录
  • 查询表中成绩在60-100分之间的记录
  • 修改wangwu的成绩为90
  • 删除表中名字叫zhangshan且成绩小于60的记录

解决需求:

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)

你可能感兴趣的:(数据库)