数据库操作
1) 查看已有数据库:show databases;
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| myemployees |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql>
2) 创建库(指定字符集):create datatabase 库名 [character set utf8];
mysql> create database test1 character set utf8;
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> create database test2 charset=utf8;
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| myemployees |
| mysql |
| performance_schema |
| sys |
| test1 |
| test2 |
+--------------------+
7 rows in set (0.00 sec)
mysql>
3) 查看创建库的语句(字符集):show create database 库名;
mysql> show create database test1;
+----------+---------------------------------------------------------------------------------------------------+
| Database | Create Database |
+----------+---------------------------------------------------------------------------------------------------+
| test1 | CREATE DATABASE `test1` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */ |
+----------+---------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql>
4) 查看当前所在数据库:select database();
mysql> select database();
+------------+
| database() |
+------------+
| NULL |
+------------+
1 row in set (0.00 sec)
5) 切换数据库:use 库名;
mysql> use test1;
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| test1 |
+------------+
1 row in set (0.00 sec)
mysql>
6) 删除数据库:drop database 库名;
mysql> drop database test2;
Query OK, 0 rows affected (0.01 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| myemployees |
| mysql |
| performance_schema |
| sys |
| test1 |
+--------------------+
6 rows in set (0.00 sec)
mysql>
7) 数据库命名规则
- 数字、字母、下划线,单不能使用纯数字
- 库名区分字母大小写
- 不能使用特殊字符和mysql关键字
数据类型:
1) 数值类型:
整形:
- tinyint:一个字节
- smallint:2个字节
- mediumint:3个字节
- int/integer:4个字节
- bigint:8个字节
浮点型:
- float: 4个字节
- double:8个字节
定点类型(精确值):
- decimal:用法decimal(M,D) M最多位数,D小数点位数
比特值类型:
- bit
2)字符串类型
- char和varchar类型
- binary和varbinary类型
- blob和text类型
- enum类型和set类型
表的基本操作
1) 创建表
create table 表名(
字段名1 数据类型,
字段名2 数据类型,
...
字段名n 数据类型,
);
- 如果设置数值为无符号,则加上unsigned;
- 如果不想字段为NULL,可以设置字段的属性为NOT NULL,在操作数据表时如果该字段的数据为NULL,就会报错;
- DEFAULT表示设置一个字段的默认值;
- AUTO_INCREMENT定义列为自增的属性,一般用于主键,数值会自动加1
- PRIMARY KEY关键字用于定义列为主键。主键的值不能重复以及不能为空。
mysql> create table class (
-> id int primary key auto_increment,
-> name varchar(30) not null,
-> age tinyint unsigned not null,
-> gender enum('M','F'),
-> score float default 0.0);
Query OK, 0 rows affected (0.05 sec)
mysql> create table interests (
-> id int primary key auto_increment,
-> name varchar(30) not null,
-> hobby set('sing','dance','draw'),
-> price decimal(8,2),
-> level char not null,
-> comment text);
Query OK, 0 rows affected (0.04 sec)
2) 查看数据表
show tables;
mysql> show tables; /* 查看当前数据库中的数据表 */
+-----------------+
| Tables_in_test1 |
+-----------------+
| class |
| interests |
+-----------------+
2 rows in set (0.00 sec)
mysql>
3) 查看已有表的创建语句
show create table 表名;
mysql> show create table class;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| class | CREATE TABLE `class` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`age` tinyint unsigned NOT NULL,
`gender` enum('M','F') DEFAULT NULL,
`score` float DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
4) 查看表结构
desc 表名
mysql> desc class;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(30) | NO | | NULL | |
| age | tinyint unsigned | NO | | NULL | |
| gender | enum('M','F') | YES | | NULL | |
| score | float | YES | | 0 | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
5) 删除表
drop table 表名;
mysql> create table test_table(
-> id int,
-> name varchar(30)
-> );
Query OK, 0 rows affected (0.04 sec)
mysql> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| class |
| interests |
| test_table |
+-----------------+
3 rows in set (0.00 sec)
mysql> drop table test_table;
Query OK, 0 rows affected (0.03 sec)
mysql> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| class |
| interests |
+-----------------+
2 rows in set (0.00 sec)
数据基本操作
1) 插入(insert)
- insert into 表名 values(值1,值2,...);
- insert into 表名 (字段1,...) values (值1,...);
mysql> insert into class values(1,'Zhangsan',20,'M',88); /* 按字段定义顺序赋值 */
Query OK, 1 row affected (0.01 sec)
mysql> insert into class (id,name,age,gender,score) values(2,'lisi',18,'F',90);/* 按字段给出的顺序赋值 */
Query OK, 1 row affected (0.00 sec)
mysql> insert into class values /* 一次插入多条记录 */
-> (3,'Wangwu',17,'F',91),
-> (4,'zhaoliu','16','M',82);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
2) 查询(select)
- select * from 表名 [where 条件];
- select 字段1, 字段名2 ... from 表名 [where 条件];
mysql> select * from class;
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 20 | M | 88 |
| 2 | lisi | 18 | F | 90 |
| 3 | Wangwu | 17 | F | 91 |
| 4 | zhaoliu | 16 | M | 82 |
+----+----------+-----+--------+-------+
4 rows in set (0.00 sec)
mysql> select name,age from class;
+----------+-----+
| name | age |
+----------+-----+
| Zhangsan | 20 |
| lisi | 18 |
| Wangwu | 17 |
| zhaoliu | 16 |
+----------+-----+
4 rows in set (0.00 sec)
where子句
where子句主要通过一定运算条件进行数据的筛选。MySQL主要有以下几种运算:
- 算术运算符
- 比较运算符
- 逻辑运算符
- 位运算符
算术运算符
- +:加
- -:减
- *:乘
- /或DIV:除
- %或MOD:取余
mysql> select name,age from class where age % 2 = 1;
+--------+-----+
| name | age |
+--------+-----+
| Wangwu | 17 |
+--------+-----+
1 row in set (0.00 sec)
mysql> select name,age from class where age - 2 >= 18;
+----------+-----+
| name | age |
+----------+-----+
| Zhangsan | 20 |
+----------+-----+
1 row in set (0.00 sec)
比较运算符
- =:等于
- <>或!=:不等于
- >:大于
- <:小于
- <=:小于等于
- >=:大于等于
- BETWEEN ... AND ...:在这个范围内
- NOT BETWEEN ... AND ...:不在这个范围内
- IN:在这个集合中
- NOT IN:不在这个集合内
- <=>:严格比较两个NULL值是否相同
- LIKE:模糊匹配
- REGEXP或RLIKE:正则匹配
- IS NULL:为空
- IS NOT NULL:不为空
mysql> select * from class where score>90;
+----+--------+-----+--------+-------+
| id | name | age | gender | score |
+----+--------+-----+--------+-------+
| 3 | Wangwu | 17 | F | 91 |
+----+--------+-----+--------+-------+
1 row in set (0.00 sec)
mysql> select * from class where age between 18 and 20;
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 20 | M | 88 |
| 2 | lisi | 18 | F | 90 |
+----+----------+-----+--------+-------+
2 rows in set (0.00 sec)
mysql> select * from class where age in (16,20);
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 20 | M | 88 |
| 4 | zhaoliu | 16 | M | 82 |
+----+----------+-----+--------+-------+
2 rows in set (0.00 sec)
逻辑运算符
- NOT或!:非
- AND:与
- OR:或
- XOR:与或
mysql> select * from class where age>16 and gender='M';
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 20 | M | 88 |
+----+----------+-----+--------+-------+
1 row in set (0.00 sec)
mysql> select * from class where not score > 90;
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 20 | M | 88 |
| 2 | lisi | 18 | F | 90 |
| 4 | zhaoliu | 16 | M | 82 |
+----+----------+-----+--------+-------+
3 rows in set (0.00 sec)
位运算符
- &:按位与
- |:按位或
- ^:按位异或
- !:取反
- <<:左移
- >>:右移
更新表记录(update)
update 表名 set 字段1=值1,字段2=值2,... where 条件;
mysql> update class set age=14,score=70 where name='Zhangsan';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from class where name='Zhangsan';
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 14 | M | 70 |
+----+----------+-----+--------+-------+
1 row in set (0.00 sec)
删除表记录(delete)
delete from 表名 where 条件;
mysql> delete from class where name='lisi';
Query OK, 1 row affected (0.00 sec)
mysql> select * from class;
+----+----------+-----+--------+-------+
| id | name | age | gender | score |
+----+----------+-----+--------+-------+
| 1 | Zhangsan | 14 | M | 70 |
| 3 | Wangwu | 17 | F | 91 |
| 4 | zhaoliu | 16 | M | 82 |
+----+----------+-----+--------+-------+
3 rows in set (0.00 sec)
表字段的操作(alter)
语法:alter table 表名 执行动作;
1) 添加字段(add)
- alter table 表名 add 字段名 数据类型;
- alter table 表名 add 字段名 数据类型 first;
- alter table 表名 add 字段名 数据类型 after 字段名;
mysql> create table test(
-> name varchar(30));
Query OK, 0 rows affected (0.05 sec)
mysql> alter table test add sex enum('M','F');
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table test add id int primary key auto_increment first;
Query OK, 0 rows affected (0.09 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table test add age tinyint after name;
Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc test;
+-------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| age | tinyint | YES | | NULL | |
| sex | enum('M','F') | YES | | NULL | |
+-------+---------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
mysql>
2) 删除字段(drop)
- alter table 表名 drop 字段名 ;
mysql> alter table test drop sex;
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc test;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| age | tinyint | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
3) 修改数据类型(modify)
- alter table 表名 modify 字段名 新数据类型;
mysql> alter table test modify age int unsigned;
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc test;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| age | int unsigned | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
4) 表重命名(rename)
- alter table 表名 rename 新表名;
mysql> alter table test rename student;
Query OK, 0 rows affected (0.03 sec)
日期时间函数
- now():返回服务器当前时间。
- curdate():返回当前日期。
- curtime():返回当前时间。
- date(date):返回指定时间的日期。
- time(date):返回指定时间的时间。
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2022-03-30 20:11:58 |
+---------------------+
1 row in set (0.00 sec)
mysql> select curdate();
+------------+
| curdate() |
+------------+
| 2022-03-30 |
+------------+
1 row in set (0.00 sec)
mysql> select curtime();
+-----------+
| curtime() |
+-----------+
| 20:12:17 |
+-----------+
1 row in set (0.00 sec)
mysql> select date('2022-03-30 20:11:58');
+-----------------------------+
| date('2022-03-30 20:11:58') |
+-----------------------------+
| 2022-03-30 |
+-----------------------------+
1 row in set (0.00 sec)
mysql> select time('2022-03-30 20:11:58');
+-----------------------------+
| time('2022-03-30 20:11:58') |
+-----------------------------+
| 20:11:58 |
+-----------------------------+
1 row in set (0.00 sec)
时间和日期类型
- DATE,DATETIME和TIMESTAMP类型
- TIME类型
- 年份类型YEAR
类型 | 大小 (字节) | 范围 | 格式 | 用途 |
---|---|---|---|---|
DATE | 3 | 1000-01-01/ 9999-12-31 | YYYY-MM-DD | 日期值 |
TIME | 3 | -838:59:59/ 838:59:59 | HH:MM:SS | 时间值或持续时间 |
YEAR | 1 | 1901/2155 | YYYY | 年份 |
DATETIME | 8 | 1000-01-01 00:00:00/ 9999-12-31 23:59:59 | YYYY-MM-DD HH:MM:SS | 混合日期和时间值 |
TIMESTAMP | 4 | 1970-01-01 00:00:00/2038 结束时间是第2147483647秒 | YYYYMMDD HHMMSSS | 混合日期和时间值,时间戳 |
时间格式
- date:"YYYY-MM-DD"
- time:"HH:MM:SS"
- datetime:"YYYY-MM-DD HH:MM:SS"
- timestamp:"YYYY-MM-DD HH:MM:SS"
注意:
- datetime:不给值 ,默认返回NULL。
- timestamp:不给值,默认返回系统当前时间。
mysql> alter table class add entry_year date;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select * from class;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | NULL |
| 3 | Wangwu | 17 | F | 91 | NULL |
| 4 | zhaoliu | 16 | M | 82 | NULL |
+----+----------+-----+--------+-------+------------+
3 rows in set (0.00 sec)
mysql> update class set entry_year='2022-03-30' where id=1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from class;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 3 | Wangwu | 17 | F | 91 | NULL |
| 4 | zhaoliu | 16 | M | 82 | NULL |
+----+----------+-----+--------+-------+------------+
3 rows in set (0.00 sec)
日期时间运算
- 语法格式:select * from 表名 where 字段名 =(时间 运算符 interval 时间间隔单位)
- 时间间隔单位:1 day | 1 hour | 2 minute | 2 year | 3 month
mysql> update class set entry_year=curdate()-interval 2 month where entry_year is null;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from class;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 3 | Wangwu | 17 | F | 91 | 2022-01-30 |
| 4 | zhaoliu | 16 | M | 82 | 2022-01-30 |
+----+----------+-----+--------+-------+------------+
3 rows in set (0.00 sec)
模糊查询和正则查询
模糊查询
1) LIKE用于在where子句进行模糊查询,SQL LIKE子句中使用百分号%来表示任何0个或多个字符,下划线_表示一个字符。
使用LIKE子句从数据表中读取数据的通用语法:
select field1, field2, ... fieldN from table_name where fieldx like condition1;
mysql> select * from class where name like 'Z%';
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 4 | zhaoliu | 16 | M | 82 | 2022-01-30 |
+----+----------+-----+--------+-------+------------+
2 rows in set (0.00 sec)
2) mysql中对正则表达式的支持有限,只支持部分正则元字符
select field1, field2, ..., fieldN from table_name where fieldx REGEXP condition1;
排序
order by子句来设定按哪个字段哪种方式来进行排序,再返回搜索结果。使用order by子句将查询数据排序后再返回数据:
select field1, field2, ..., fieldN from table_name where field1 order by field1 [ASC [DESC]]
默认情况ASC表示升序,DESC表示降序。
mysql> select * from class order by age;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 4 | zhaoliu | 16 | M | 82 | 2022-01-30 |
| 3 | Wangwu | 17 | F | 91 | 2022-01-30 |
+----+----------+-----+--------+-------+------------+
3 rows in set (0.00 sec)
分页
limit子句用于限制由select语句返回的数据数量或者UPDATE,DELETE语句的操作数量。
带有limit子句的select语句的基本语法如下:
select column1, column2, ... ,columnN
from table_name
where filed
limit [num]
mysql> select * from class limit 1;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
+----+----------+-----+--------+-------+------------+
1 row in set (0.00 sec)
联合查询
union操作用于连接两个以上的SELECT语句的结果组合到一个结果集合中。多个select语句会删除重复的数据。
union操作符语法格式:
select expression1, expression2, ..., expressionN
from tables
[where condtions]
union [ALL | DISTINCT]
select expression1, expression2, ..., expressionN
from tables
[where condtions]
mysql> select * from class where id=1
-> union
-> select * from class where id=3;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 3 | Wangwu | 17 | F | 91 | 2022-01-30 |
+----+----------+-----+--------+-------+------------+
2 rows in set (0.00 sec)
数据库备份
1) 备份命令格式:mysqldump -u用户名 -p 源库名 > 路径/备份名.sql
- --all databases: 备份所有库
- 库名: 备份单个库
- -B 库1 库2 库3 : 备份多个库
- 库名 表1 表2 表3 :备份指定库的多个表
[root@bjAli mysql]# ls
[root@bjAli mysql]# mysqldump -uroot -p test1 > test1.sql
Enter password:
[root@bjAli mysql]# ls
test1.sql
[root@bjAli mysql]#
2) 恢复命令格式:mysql -u用户名 -p 目标库名 < ***.sql
- --one-database:从所有库备份中恢复一个库
mysql> drop database test1;
Query OK, 3 rows affected (0.06 sec)
mysql> create database student;
Query OK, 1 row affected (0.01 sec)
mysql> quit
Bye
[root@bjAli mysql]# mysql -uroot -p student < test1.sql
Enter password:
[root@bjAli mysql]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 89
Server version: 8.0.28 MySQL Community Server - GPL
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use student;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+-------------------+
| Tables_in_student |
+-------------------+
| class |
| interests |
| student |
+-------------------+
3 rows in set (0.01 sec)
mysql> select * from class;
+----+----------+-----+--------+-------+------------+
| id | name | age | gender | score | entry_year |
+----+----------+-----+--------+-------+------------+
| 1 | Zhangsan | 14 | M | 70 | 2022-03-30 |
| 3 | Wangwu | 17 | F | 91 | 2022-01-30 |
| 4 | zhaoliu | 16 | M | 82 | 2022-01-30 |
+----+----------+-----+--------+-------+------------+
3 rows in set (0.00 sec)