mySQL基础

mySQL基础

关系型数据库介绍

数据结构模型

数据结构模型主要有

  • 层次模型
  • 网状结构
  • 关系模型

关系模型

  • 二维关系:row,column

数据库管理系统:DBMS
关系:Relational,RDBMS

RDBMS专业名词

常见的关系型数据库管理系统:

  • MySQL:MySQL,MariaDB,Percona-Server
  • PostgreSQL:简称为pgsql
  • Oracle
  • MSSQL

SQL:Structure Query Language,结构化查询语言

约束:constraint,向数据表提供的数据要遵守的限制

  • 主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)。
    • 一个表只能存在一个
  • 惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)
    • 一个表可以存在多个
  • 外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
  • 检查性约束

索引:将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储

关系型数据库的常见组件

关系型数据库的常见组件有:

  • 数据库:database
  • 表:table,由行(row)和列(column)组成
  • 索引:index
  • 视图:view
  • 用户:user
  • 权限:privilege
  • 存储过程:procedure
  • 存储函数:function
  • 触发器:trigger
  • 事件调度器:event scheduler

SQL语句

SQL语句有三种类型:

  • DDL:Data Defination Language,数据定义语言
  • DML:Data Manipulation Language,数据操纵语言
  • DCL:Data Control Language,数据控制语言
SQL语句类型 对应操作
DDL CREATE:创建
DROP:删除
ALTER:修改
DML INSERT:向表中插入数据
DELETE:删除表中数据
UPDATE:更新表中数据
SELECT:查询表中数据
DCL GRANT:授权
REVOKE:移除授权

mysql安装与配置

mysql安装

mysql安装方式有三种:

  • 源代码:编译安装
  • 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
  • 程序包管理器管理的程序包:
    • rpm:有两种
      • OS Vendor:操作系统发行商提供的
      • 项目官方提供的
    • deb
我们使用第一种方法
[root@www ~]# yum -y install mariadb*

#配置mysql的yum源
wget -O /usr/src/mysql57-community-release-el7-10.noarch.rpm 
http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
rpm -Uvh /usr/src/mysql57-community-release-el7-10.noarch.rpm

#安装mysql5.7
yum -y install mysql-community-server mysql-community-client  
mysql-community-common mysql-community-devel

mysql配置

安装mariadb
启动mariadb查看端口号

[root@www ~]# yum -y install mariadb*
[root@www ~]# systemctl enable --now mariadb
Created symlink /etc/systemd/system/mysql.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/mysqld.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/multi-user.target.wants/mariadb.service → /usr/lib/systemd/system/mariadb.service.
[root@www ~]# ss -tanlp
State    Recv-Q    Send-Q        Local Address:Port         Peer Address:Port                                                                                     
LISTEN   0         128                 0.0.0.0:22                0.0.0.0:*        users:(("sshd",pid=1067,fd=5))                                                  
LISTEN   0         80                  0.0.0.0:3306              0.0.0.0:*        users:(("mysqld",pid=7813,fd=21))                                               
LISTEN   0         128                    [::]:22                   [::]:*        users:(("sshd",pid=1067,fd=7))                                                  

mysql的程序组成

  • 客户端
    • mysql:CLI交互式客户端程序
    • mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
    • mysqldump:mysql备份工具
    • mysqladmin
  • 服务器端
    • mysqld

mysql工具使用

//语法:mysql [OPTIONS] [database]
//常用的OPTIONS:
    -uUSERNAME      //指定用户名,默认为root
    -hHOST          //指定服务器主机,默认为localhost,推荐使用ip地址
    -pPASSWORD      //指定用户的密码
    -P#             //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
    -V              //查看当前使用的mysql版本
    -e          //不登录mysql执行sql语句后退出,常用于脚本

设置密码

MariaDB [(none)]> set password = password ('123456');
Query OK, 0 rows affected (0.000 sec)

修改密码

MariaDB [(none)]> alter user root@localhost identified by '654321';
Query OK, 0 rows affected (0.000 sec)

注意,不推荐直接在命令行里直接用-pPASSWORD的方式登录,而是使用-p选项,然后交互式输入密码

使用命令 mysql_secure_installation安全初始化

[root@www ~]# mysql_secure_installation 

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

You already have a root password set, so you can safely answer 'n'.

Change the root password? [Y/n] n
 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] 
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] n
 ... skipping.

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] n
 ... skipping.

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] n
 ... skipping.

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

查看数据库

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.001 sec)

MariaDB [(none)]> quit
Bye
[root@www ~]# mysql -u root -p654321 -e 'show databases;'
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+

服务器监听的两种socket地址

socket类型 说明
ip socket 默认监听在tcp的3306端口,支持远程通信
unix sock 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock)
仅支持本地通信
server地址只能是:localhost,127.0.0.1

mysql数据库操作

DDL操作

数据库操作

//创建数据库
//语法:MariaDB [(none)]> create database +name;
创建名字为:[school] 的数据库

MariaDB [(none)]> create database school;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
+--------------------+
4 rows in set (0.000 sec)
再次创建名为[school]的数据库

MariaDB [(none)]> create database school;
ERROR 1007 (HY000): Can't create database 'school'; database exists

报错
发现无法创建
需要在数据库名字前加上[if not exists]

MariaDB [(none)]> create database if not exists school;
Query OK, 0 rows affected, 1 warning (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
+--------------------+
4 rows in set (0.000 sec)

可以看到虽然没有报错,但是并没有创建新的数据库
//删除数据库
//语法:drop database [if exists] +name;
//删除数据库
MariaDB [(none)]> drop database school;
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.000 sec)

MariaDB [(none)]> drop database if exists school;
Query OK, 0 rows affected, 1 warning (0.000 sec)

表操作

//创建表
//语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';
//在数据库school里创建表school

MariaDB [school]> CREATE TABLE student(id int not null,name varchar(50) null,age tinyint);
Query OK, 0 rows affected (0.004 sec)

MariaDB [school]> show tables;
+------------------+
| Tables_in_school |
+------------------+
| student          |
+------------------+
1 row in set (0.000 sec)

MariaDB [school]> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(50) | YES  |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.001 sec)

//删除表
//语法:DROP TABLE [ IF EXISTS ] 'table_name';
//删除表

MariaDB [school]> drop table student;
Query OK, 0 rows affected (0.003 sec)

MariaDB [school]> show tables;
Empty set (0.000 sec)

帮助文档命令:
创建数据库帮助文档:help create database;
创建表帮助文档:help create table;

DCL操作

创建授权grant

权限类型(priv_type)

权限类型 代表什么?
ALL 所有权限
SELECT 读取内容的权限
INSERT 插入内容的权限
UPDATE 更新内容的权限
DELETE 删除内容的权限

指定要操作的对象db_name.table_name

表示方式 意义
  • . *|所有库的所有表
    db_name |指定库的所有表
    db_name.table_name |指定库的指定表

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

MariaDB [(none)]> grant all on *.* to 'root'@'192.168.23.1' identified by '654321';
Query OK, 0 rows affected (0.000 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.000 sec)
//授权root用户在数据库本机上登录访问所有数据库
mysql> GRANT ALL ON *.* TO 'root'@'localhost' IDENTIFIED BY '654321';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> GRANT ALL ON *.* TO 'root'@'127.0.0.1' IDENTIFIED BY '654321';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//授权root用户在172.16.12.129上远程登录访问rootge数据库
mysql> GRANT ALL ON wangqingge.* TO 'root'@'192.168.23.1' IDENTIFIED BY '654321';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//授权root用户在所有位置上远程登录访问root数据库
mysql> GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY '654321';
Query OK, 0 rows affected, 1 warning (0.00 sec)

查看授权

查看当前登录用户的授权信息

MariaDB [(none)]> show grants;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*2A032F7C5BA932872F0F045E0CF6B53CF702F2C5' WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION                                                                          |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.000 sec)

查看指定用户的授权信息

//show grants for +指定用户名

MariaDB [(none)]> show grants for 'root'@'192.168.23.1';
+-------------------------------------------------------------------------------------------------------------------------+
| Grants for root@192.168.23.1                                                                                            |
+-------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.23.1' IDENTIFIED BY PASSWORD '*2A032F7C5BA932872F0F045E0CF6B53CF702F2C5' |
+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)

取消授权REVOKE

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

mysql> REVOKE ALL ON *.* FROM 'wangqing'@'172.16.12.129';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

注意:mysql服务进程启动时会读取mysql库中的所有授权表至内存中:

  • GRANT或REVOKE等执行权限操作会保存于表中,mysql的服务进程会自动重读授权表,并更新至内存中
  • 对于不能够或不能及时重读授权表的命令,可手动让mysql的服务进程重读授权表
mysql> FLUSH PRIVILEGES;

DML操作

DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT),均属针对表的操作。

INSERT语句

MariaDB [school]> insert into student values(1,'tom',15);
Query OK, 1 row affected (0.001 sec)

MariaDB [school]> select * from student;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | tom  |   15 |
+----+------+------+
1 row in set (0.000 sec)

一次插入多条数据
MariaDB [school]> insert into student values(4,'b',24),(5,'c',22),(6,'d',21),(7,'e',19);
Query OK, 4 rows affected (0.001 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [school]> select * from student;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | tom  |   15 |
|  2 | a    |   15 |
|  1 | tom  |   15 |
|  4 | b    |   24 |
|  5 | c    |   22 |
|  6 | d    |   21 |
|  7 | e    |   19 |
+----+------+------+
7 rows in set (0.000 sec)

设置自动增长

MariaDB [school]> create table teacher(id int not null primary key auto_increment,name varchar(20) not null,age tinyint,salary float);
Query OK, 0 rows affected (0.033 sec)
MariaDB [school]> select * from teacher;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
+----+------+------+--------+
2 rows in set (0.000 sec)

MariaDB [school]> insert into teacher(name,age,salary) values('b1',37,5000),('b2',37,4800),('c1',40,5000),('c2',55,9000);
Query OK, 4 rows affected (0.001 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [school]> select * from teacher;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   37 |   4800 |
|  5 | c1   |   40 |   5000 |
|  6 | c2   |   55 |   9000 |
+----+------+------+--------+
6 rows in set (0.000 sec)

update语句

//DML操作之改操作update
//语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

MariaDB [school]> select * from teacher;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   37 |   4800 |
|  5 | c1   |   40 |   5000 |
|  6 | c2   |   55 |   9000 |
+----+------+------+--------+
6 rows in set (0.000 sec)

MariaDB [school]> update teacher set age = 35 where id = 4;
Query OK, 1 row affected (0.035 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [school]> select * from teacher;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   35 |   4800 |
|  5 | c1   |   40 |   5000 |
|  6 | c2   |   55 |   9000 |
+----+------+------+--------+
6 rows in set (0.000 sec)

SELECT语句

字段column表示法

表示符 代表什么?
  • |所有字段
    as |字段别名,如col1 AS alias1
    当表名很长时用别名代替

条件判断语句WHERE

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

ORDER BY:排序,默认为升序(ASC)

ORDER BY语句 意义
ORDER BY ‘column_name' 根据column_name进行升序排序
ORDER BY 'column_name' DESC 根据column_name进行降序排序
ORDER BY ’column_name' LIMIT 2 根据column_name进行升序排序
并只取前2个结果
ORDER BY ‘column_name' LIMIT 1,2 根据column_name进行升序排序
并且略过第1个结果取后面的2个结果
//DML操作之查操作select
//语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

查看所有字段
MariaDB [school]> select * from teacher;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   35 |   4800 |
|  5 | c1   |   40 |   5000 |
|  6 | c2   |   55 |   9000 |
+----+------+------+--------+
6 rows in set (0.000 sec)

查看指定字段
MariaDB [school]> select name,salary from teacher;
+------+--------+
| name | salary |
+------+--------+
| a1   |   3000 |
| a2   | 3500.5 |
| b1   |   5000 |
| b2   |   4800 |
| c1   |   5000 |
| c2   |   9000 |
+------+--------+
6 rows in set (0.000 sec)

as指定字段别名
MariaDB [school]> select name as '姓名',salary as '工资' from teacher;
+--------+--------+
| 姓名   | 工资   |
+--------+--------+
| a1     |   3000 |
| a2     | 3500.5 |
| b1     |   5000 |
| b2     |   4800 |
| c1     |   5000 |
| c2     |   9000 |
+--------+--------+
6 rows in set (0.000 sec)

查询工资大于4000的人

MariaDB [school]> select name  from teacher where salary > 4000;
+------+
| name |
+------+
| b1   |
| b2   |
| c1   |
| c2   |
+------+
4 rows in set (0.000 sec)

查询年龄在31到40岁之间的人

MariaDB [school]> select * from teacher where age between 31 and 40;
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   35 |   4800 |
|  5 | c1   |   40 |   5000 |
+----+------+------+--------+
3 rows in set (0.000 sec)

查询名字以a开头的人

MariaDB [school]> select * from teacher where name like 'a%';
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  2 | a2   |   30 | 3500.5 |
+----+------+------+--------+
2 rows in set (0.000 sec)

查询名字以1结尾的人

MariaDB [school]> select * from teacher where name like '%1';
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  3 | b1   |   37 |   5000 |
|  5 | c1   |   40 |   5000 |
+----+------+------+--------+
3 rows in set (0.000 sec)

查询名字以b开头,以1结尾的人

MariaDB [school]> select * from teacher where name like '%1' or name like 'b%';
+----+------+------+--------+
| id | name | age  | salary |
+----+------+------+--------+
|  1 | a1   |   30 |   3000 |
|  3 | b1   |   37 |   5000 |
|  4 | b2   |   35 |   4800 |
|  5 | c1   |   40 |   5000 |
+----+------+------+--------+
4 rows in set (0.000 sec)

空与空格的区别

MariaDB [school]> alter table teacher add department varchar(20) null;
Query OK, 0 rows affected (0.001 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [school]> select * from teacher 
    -> ;
+----+------+------+--------+------------+
| id | name | age  | salary | department |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
|  6 | c2   |   55 |   9000 | NULL       |
+----+------+------+--------+------------+
6 rows in set (0.000 sec)
MariaDB [school]> update teacher set department =' ' where id = 6;
Query OK, 1 row affected (0.000 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [school]> select * from teacher 
    -> ;
+----+------+------+--------+------------+
| id | name | age  | salary | department |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
|  6 | c2   |   55 |   9000 |            |
+----+------+------+--------+------------+
6 rows in set (0.000 sec)
MariaDB [school]> select * from teacher where dapartment is not null;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  6 | c2   |   55 |   9000 |            |
+----+------+------+--------+------------+
1 row in set (0.000 sec)

MariaDB [school]> select * from teacher where dapartment is  null;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
+----+------+------+--------+------------+
5 rows in set (0.000 sec)

按年龄排序(默认升序)

MariaDB [school]> select * from teacher order by age;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
|  6 | c2   |   55 |   9000 |            |
+----+------+------+--------+------------+
6 rows in set (0.000 sec)

降序
MariaDB [school]> select * from teacher order by age desc;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  6 | c2   |   55 |   9000 |            |
|  5 | c1   |   40 |   5000 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
+----+------+------+--------+------------+
6 rows in set (0.000 sec)

工资前3排序

MariaDB [school]> select * from teacher order by salary desc limit 3;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  6 | c2   |   55 |   9000 |            |
|  5 | c1   |   40 |   5000 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
+----+------+------+--------+------------+
3 rows in set (0.000 sec)

delete语句

//DML操作之删操作delete
//语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

MariaDB [school]> select * from teacher;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
|  6 | c2   |   55 |   9000 |            |
|  7 | d1   |   25 |   NULL | NULL       |
+----+------+------+--------+------------+
7 rows in set (0.000 sec)

MariaDB [school]> delete from teacher where salary is nell;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'nell' at line 1
MariaDB [school]> delete from teacher where salary is NULL;
Query OK, 1 row affected (0.001 sec)

MariaDB [school]> select * from teacher;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
|  6 | c2   |   55 |   9000 |            |
+----+------+------+--------+------------+
6 rows in set (0.000 sec)
MariaDB [school]> delete from teacher where dapartment is not NULL;
Query OK, 1 row affected (0.001 sec)

MariaDB [school]> select * from teacher;
+----+------+------+--------+------------+
| id | name | age  | salary | dapartment |
+----+------+------+--------+------------+
|  1 | a1   |   30 |   3000 | NULL       |
|  2 | a2   |   30 | 3500.5 | NULL       |
|  3 | b1   |   37 |   5000 | NULL       |
|  4 | b2   |   35 |   4800 | NULL       |
|  5 | c1   |   40 |   5000 | NULL       |
+----+------+------+--------+------------+
5 rows in set (0.000 sec)

删除整个表

MariaDB [school]> delete from teacher; //只删除表中的数据

truncate语句

语句类型 特点
delete DELETE删除表内容时仅删除内容,但会保留表结构
DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项
可以通过回滚事务日志恢复数据
非常占用空间
truncate 删除表中所有数据,且无法恢复
表结构、约束和索引等保持不变,新添加的行计数值重置为初始值
执行速度比DELETE快,且使用的系统和事务日志资源少
通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放
对于有外键约束引用的表,不能使用TRUNCATETABLE删除数据
不能用于加入了索引视图的表
//语法:TRUNCATE table_name;

作业

  1. 搭建mysql服务
[root@www]# mount /dev/cdrom /mnt/
mount: /mnt: WARNING: device write-protected, mounted read-only.
[root@www ~]# yum -y install mariadb*
[root@www ~]# systemctl enable --now mariadb

  1. 创建一个以你名字为名的数据库,并创建一张表student,该表包含三个字段(id,name,age),表结构如下:
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.01 sec)
MariaDB [(none)]> create database if not exists yc;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> use yc;
Database changed

MariaDB [yc]> create table student(id int(11) not null primary key auto_increment,name varchar(100) not null,age tinyint(4));
Query OK, 0 rows affected (0.112 sec)

MariaDB [yc]> 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.001 sec)
  1. 查看下该新建的表有无内容(用select语句)
MariaDB [yc]> select * from student;
Empty set (0.000 sec)
  1. 往新建的student表中插入数据(用insert语句),结果应如下所示:
+----+-------------+------+
| 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 | chenshuo    |   10 |
|  9 | wangwu      |    3 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
MariaDB [yc]> insert into student(name,age) values('tom',20),('jerry',23),('wangqing',25),('sean',28),('zhangshan',26),('zhangshan',20),('lisi',null),('chengshuo',10),('wangwu',3),('qiuyi',15),('qiuxiaotian',20);
Query OK, 11 rows affected (0.001 sec)
Records: 11  Duplicates: 0  Warnings: 0

MariaDB [yc]> 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.000 sec)
  1. 修改lisi的年龄为50
MariaDB [yc]> update student set age = 50 where id = 7;
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yc]> 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        |   50 |
|  8 | chengshuo   |   10 |
|  9 | wangwu      |    3 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
11 rows in set (0.000 sec)
  1. 以age字段降序排序
MariaDB [yc]> select * from student order by age desc;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  7 | lisi        |   50 |
|  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 |
+----+-------------+------+
11 rows in set (0.000 sec)
  1. 查询student表中年龄最小的3位同学跳过前2位
MariaDB [yc]> select * from student order by age limit 2,3;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
| 10 | qiuyi       |   15 |
|  1 | tom         |   20 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
3 rows in set (0.000 sec)
  1. 查询student表中年龄最大的4位同学
MariaDB [yc]> select * from student order by age desc limit 4;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  7 | lisi      |   50 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | wangqing  |   25 |
+----+-----------+------+
4 rows in set (0.000 sec)
  1. 查询student表中名字叫zhangshan的记录
MariaDB [yc]> select * from student where name = 'zhangshan';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
2 rows in set (0.000 sec)
  1. 查询student表中名字叫zhangshan且年龄大于20岁的记录
MariaDB [yc]> select * from student where name = 'zhangshan' and age>20;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.000 sec)
  1. 查询student表中年龄在23到30之间的记录
MariaDB [yc]> select * from student where age between 23 and 30; 
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | wangqing  |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
4 rows in set (0.000 sec)
  1. 修改wangwu的年龄为100
MariaDB [yc]> update student set age = 100 where id = 9;
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yc]> 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        |   50 |
|  8 | chengshuo   |   10 |
|  9 | wangwu      |  100 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
11 rows in set (0.000 sec)
  1. 删除student中名字叫zhangshan且年龄小于等于20的记录
ariaDB [yc]> delete from student where name = 'zhangshan' and age<=20;
Query OK, 1 row affected (0.001 sec)

MariaDB [yc]> select * from student;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  1 | tom         |   20 |
|  2 | jerry       |   23 |
|  3 | wangqing    |   25 |
|  4 | sean        |   28 |
|  5 | zhangshan   |   26 |
|  7 | lisi        |   50 |
|  8 | chengshuo   |   10 |
|  9 | wangwu      |  100 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
10 rows in set (0.000 sec)
原文地址:https://www.cnblogs.com/Ycqifei/p/14199768.html