当前位置: 首页 > news >正文

MySQL的使用

MySQL的使用

  • 一、mysql中的周边命令
    • 1. 检查版本
    • 2. 查看字符集
    • 3. 查看客户端连接
    • 4. 查看最后一条警告消息
  • 二、数据库、数据表的管理
    • 1. 语法规则
    • 2. 数据库
      • 2.1 查看数据库
      • 2.2 创建数据库
      • 2.3 选择数据库
      • 2.4 查看创建数据库命令
      • 2.5 创建库时添加字符集
      • 2.6 修改数据库字符集
      • 2.7 删除数据库
    • 3. 表
      • 3.1 查看表
      • 3.2 创建表
      • 3.3 数据类型
        • 3.3.1 整数类型
        • 3.3.2 浮点类型(小数)
        • 3.3.3 字符串类型
        • 3.3.4 日期时间类型
        • 3.3.5 枚举和集合类型
      • 3.4 常见的约束
        • 3.4.1 非空约束(NOT NULL)
        • 3.4.2 默认值约束(DEFAULT)
        • 3.4.3 唯一约束(UNIQUE)
        • 3.4.4 主键约束(PRIMARY KEY)
        • 3.4.5 外键约束(FOREIGN KEY)
      • 3.5 复制表结构
      • 3.6 删除表
      • 3.7 修改表
      • 3.8 表数据操作
  • 总结


一、mysql中的周边命令

1. 检查版本

root@mysql 14: 47>select version();
±----------+
| version() |
±----------+
| 8.0.42 |
±----------+
1 row in set (0.00 sec)


2. 查看字符集

show variables;
show variables like “%char%”;
show variables like "%char%"\G
****************** 1. row *****************
Variable_name: character_set_client
Value: utf8mb4

GBK =》 中文
UTF8 => 全世界


3. 查看客户端连接

root@mysql 14: 55>show processlist\G
*************************** 1. row ***************************
Id: 5
User: event_scheduler
Host: localhost
db: NULL
Command: Daemon
Time: 766
State: Waiting on empty queue
Info: NULL
*************************** 2. row ***************************
Id: 14
User: root
Host: localhost
db: mysql
Command: Query
Time: 0
State: init
Info: show processlist
2 rows in set, 1 warning (0.00 sec)


4. 查看最后一条警告消息

root@mysql 14: 58>show warnings\G
*************************** 1. row ***************************
Level: Error
Code: 1064
Message: 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 ‘warning’ at line 1
1 row in set (0.00 sec)


二、数据库、数据表的管理

1. 语法规则

  • MySQL命令是以分号结束
  • MySQL命令关键字不区分大小写, 按MySQL规范建议大写
  • MySQL数据库名、表名区分大小写
  • 查看帮助 命令前加help
    help show;

2. 数据库

一个数据库就是一个目录

2.1 查看数据库

SHOW DATABASES;

2.2 创建数据库

CREATE DATABASE <数据库名>;

root@sys 15: 07>CREATE DATABASE test;
Query OK, 1 row affected (0.01 sec)

2.3 选择数据库

USE <数据库名>;

root@sys 15: 08>use test;
Database changed
root@test 15: 08>

2.4 查看创建数据库命令

SHOW CREATE DATABASE <数据库名>;

root@test 15: 09>SHOW CREATE DATABASE test\G
*************************** 1. row ***************************
Database: test
Create Database: CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION=‘N’ */

2.5 创建库时添加字符集

CREATE DATABASE <数据库名> DEFAULT CHARACTER SET <字符集>;

root@test 15: 09>CREATE DATABASE test2 DEFAULT CHARACTER SET GBK;
Query OK, 1 row affected (0.01 sec)
 
root@test 15: 10>SHOW CREATE DATABASE test2\G
*************************** 1. row ***************************
Database: test2
Create Database: CREATE DATABASE `test2` /*!40100 DEFAULT CHARACTER SET gbk / /!80016 DEFAULT ENCRYPTION=‘N’ */
1 row in set (0.00 sec)

2.6 修改数据库字符集

ALTER DATABASE test3 DEFAULT CHARACTER SET UTF8;

2.7 删除数据库

DROP DATABASE test3;


3. 表

一个表就是一个文件:表中存储具体的数据

3.1 查看表

SHOW TABLES;

查看表结构
DESC <表名>;

查看完整建表语句
SHOW CREATE TABLE <表名>;

3.2 创建表

CREATE TABLE <表名> (
字段名 字段类型 字段约束,
字段名 字段类型 字段约束
);

列名:大小写下划线,小写+下划线
数据类型:要存储的数据是什么类型
name => string
列约束:完整性(NOT NULL), 默认值,主键…


3.3 数据类型

正确地选择数据类型

  • 优化存储空间:节省磁盘空间
  • 提供查询性能
  • 保证数据完整性
  • 提高数据库可维护性
3.3.1 整数类型
  • TINYINT 1字节 -128~127 0~255
  • SMALLINT 2字节
  • MEDIUMINT 3字节
  • INT 4字节
  • BIGINT 8字节

属性

  • TYPE(n) => 显示宽度 n=5
  • ZEROFILL => 零填充 00127 (适合无符号类型)
  • UNSIGNED => 无符号

创建表

root@test 15: 20>CREATE TABLE test_int(
-> age TINYINT UNSIGNED,
-> num1 INT(5) UNSIGNED ZEROFILL,
-> num2 INT ZEROFILL);

查看完整建表语句,含有默认信息和字符集信息

root@test 15: 34>SHOW CREATE TABLE test_int\G
*************************** 1. row ***************************
Table: test_int
Create Table: CREATE TABLE `test_int` (
`age` tinyint unsigned DEFAULT NULL,
`num1` int(5) unsigned zerofill DEFAULT NULL,
`num2` int(10) unsigned zerofill DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)

查看表结构

root@test 15: 36>DESC test_int;
+-------+---------------------------+------+-----+---------+-------+
| Field | Type                      | Null | Key | Default | Extra |
+-------+---------------------------+------+-----+---------+-------+
| age   | tinyint unsigned          | YES  |     | NULL    |       |
| num1  | int(5) unsigned zerofill  | YES  |     | NULL    |       |
| num2  | int(10) unsigned zerofill | YES  |     | NULL    |       |
+-------+---------------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

插入数据

root@test 15: 36>INSERT INTO test_int VALUES (10, 99, 99);
Query OK, 1 row affected (0.00 sec)
root@test 15: 37>INSERT INTO test_int VALUES (10, 99, 99),(11,88,888);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
root@test 15: 37>INSERT INTO test_int (age, num1) VALUES (12, 111);
Query OK, 1 row affected (0.01 sec)

查询数据

root@test 15: 38>SELECT * FROM test_int;
+------+-------+------------+
| age  | num1  | num2       |
+------+-------+------------+
|   10 | 00099 | 0000000099 |
|   10 | 00099 | 0000000099 |
|   11 | 00088 | 0000000888 |
|   12 | 00111 |       NULL |
+------+-------+------------+

当 sql_mode 包含 STRICT_TRANS_TABLES 时,MySQL 会严格检查数据范围,超出范围直接报错

root@test 15: 41>INSERT INTO test_int (age, num1) VALUES (256, 111);
ERROR 1264 (22003): Out of range value for column ‘age’ at row 1

设置为宽松模式

root@test 15: 41>SET SESSION sql_mode=“NO_ENGINE_SUBSTITUTION”;
Query OK, 0 rows affected (0.00 sec)
root@test 15: 44>INSERT INTO test_int (age, num1) VALUES (256, 111);
Query OK, 1 row affected, 1 warning (0.00 sec)


3.3.2 浮点类型(小数)
  • float 4字节 默认长度7 单精度浮点型
  • double 8字节 默认长度17 双精度浮点型
  • decimal 精确的浮点数

float/double 指定显示宽度和小数位数,如果没有指定按实际精度来处理
decimal 不指定显示宽度和小数位数,默认为(10,0)

创建表

root@test 15: 45>CREATE TABLE test_float(
-> float_num1 FLOAT,
-> double_num1 double,
-> decimal_num1 decimal,
-> float_num2 float(10,2),
-> double_num2 double(10,2),
-> decimal_num2 decimal(10,2)
-> );

插入数据

root@test 16: 12>insert into test_float values(6.6666666,6.6666666,6.6666666,6.6666666,6.6666666,6.6666666);
Query OK, 1 row affected, 2 warnings (0.01 sec)

查看数据

   root@test 16: 13>SELECT * FROM test_float;
+------------+-------------+--------------+------------+-------------+--------------+
| float_num1 | double_num1 | decimal_num1 | float_num2 | double_num2 | decimal_num2 |
+------------+-------------+--------------+------------+-------------+--------------+
|    6.66667 |   6.6666666 |            7 |       6.67 |        6.67 |         6.67 |
+------------+-------------+--------------+------------+-------------+--------------+
1 row in set (0.00 sec)

3.3.3 字符串类型
  • CHAR(N) 固定长度字符串,手机号、身份证…
  • VARCHAR(N) 可变长字符串,标题、昵称(灵活,省空间,效率稍微差一点)
  • TEXT 用于存储大块文本 0-65535
  • TINYTEXT 小文本 0-255
  • MEDIUMTEXT 中等文本
  • LONGTEXT 超大文本
  • BLOB 存储二进制数据(图片、音频、视频)
  • JSON

创建表

root@test 16: 21>CREATE TABLE test_string(
-> name char(4),
-> title varchar(255),
-> content text
-> );

插入数据

root@test 16: 31>insert into test_string values (“abcdefg”, “abcefg”, “abcefg”);
Query OK, 1 row affected, 1 warning (0.00 sec)

查询数据

root@test 16: 32>select * from test_string;
+------+--------+---------+
| name | title  | content |
+------+--------+---------+
| abcd | abcefg | abcefg  |
+------+--------+---------+
1 row in set (0.01 sec)

创建一个人员表:person
用户名:username
邮箱:email
性别:sex
年龄:age

CHAR(1) => 此处1为宽度

root@test 16: 32>CREATE TABLE person(
-> username char(4),
-> email varchar(20),
-> sex char(1),
-> age tinyint unsigned
-> );
Query OK, 0 rows affected (0.03 sec)

root@test 16: 49>insert person values(‘zf’, ‘zf@qq.com’, ‘m’, 20);
Query OK, 1 row affected (0.00 sec)
root@test 16: 51>insert person values(‘zf’, ‘zf@qq.com’, ‘男’, 20);
Query OK, 1 row affected (0.00 sec)

root@test 16: 51>SELECT * FROM person;
+----------+-----------+------+------+
| username | email     | sex  | age  |
+----------+-----------+------+------+
| zf       | zf@qq.com | m    |   20 |
+----------+-----------+------+------+
1 row in set (0.00 sec)

3.3.4 日期时间类型
  • DATE 3字节 yyyy-MM-dd 日期
  • TIME 3字节 HH:mm:ss 时间
  • year 1字节 yyyy 年份
  • datetime 8字节 yyyy-MM-dd HH:mm:ss
  • timestamp 4字节 yyyy-MM-dd HH:mm:ss (显示数据依赖当前时区)

创建表

root@test 16: 53>create table test_time(
-> date_value DATE,
-> time_value TIME,
-> year_value YEAR,
-> datetime_value DATETIME,
-> timestamp_value TIMESTAMP
-> );
Query OK, 0 rows affected (0.02 sec)

插入数据

root@test 16: 58>INSERT INTO test_time VALUES (now(),now(),now(),now(),now());
Query OK, 1 row affected, 1 warning (0.00 sec)

查看当前时间

root@test 16: 59>SELECT now();
+---------------------+
| now()               |
+---------------------+
| 2025-06-27 16:59:42 |
+---------------------+
1 row in set (0.00 sec)

查询数据

root@test 16: 59>select * from test_time;
+------------+------------+------------+---------------------+---------------------+
| date_value | time_value | year_value | datetime_value      | timestamp_value     |
+------------+------------+------------+---------------------+---------------------+
| 2025-06-27 | 16:59:24   |       2025 | 2025-06-27 16:59:24 | 2025-06-27 16:59:24 |
+------------+------------+------------+---------------------+---------------------+
1 row in set (0.00 sec)

创建一个文章表:articles
文章标题:title
文章正文:content
发布时间:publish
浏览量: views
作者: author

root@test 17: 00>CREATE TABLE articles(
-> title VARCHAR(128),
-> content TEXT,
-> publish DATETIME,
-> views INT UNSIGNED,
-> author CHAR(4)
-> );

root@test 17: 14>insert into articles VALUES (“十万个为什么”, "正文 ", “2014-10-01”, 100, “韩启德” );
Query OK, 1 row affected, 0 warning (0.01 sec)

root@test 17: 14>SELECT * FROM articles;
+--------------------+---------+---------------------+-------+-----------+
| title              | content | publish             | views | author    |
+--------------------+---------+---------------------+-------+-----------+
| 十万个为什么       | 正文    | 2014-10-10 00:00:00 |   100 | 韩启德    |
| 十万个为什么       | 正文    | 2014-10-10 00:00:00 |   100 | 韩启德    |
+--------------------+---------+---------------------+-------+-----------+
2 rows in set (0.00 sec)

root@test 17: 14>insert into articles VALUES (“十万个为什么”, "正文 ", “2014-10”, 100, “韩启德” );
Query OK, 1 row affected, 1 warning (0.01 sec)

宽松模式将非法日期转换为 0000-00-00,并记录警告

root@test 17: 14>SELECT * FROM articles;
+--------------------+---------+---------------------+-------+-----------+
| title              | content | publish             | views | author    |
+--------------------+---------+---------------------+-------+-----------+
| 十万个为什么       | 正文    | 2014-10-10 00:00:00 |   100 | 韩启德    |
| 十万个为什么       | 正文    | 2014-10-10 00:00:00 |   100 | 韩启德    |
| 十万个为什么       | 正文    | 0000-00-00 00:00:00 |   100 | 韩启德    |
+--------------------+---------+---------------------+-------+-----------+
3 rows in set (0.00 sec)

3.3.5 枚举和集合类型
  • ENUM 枚举 多选一 男/女/保密
  • SET 集合 多选多 唱歌、跳舞、健身、跑步…

创建表

root@test 17: 14>CREATE TABLE test_enum_set(
-> name varchar(4),
-> sex enum(‘男’,‘女’,‘保密’),
-> hobby SET(‘唱歌’,‘跳舞’,‘运动’,‘阅读’)
-> );
Query OK, 0 rows affected (0.03 sec)

插入数据

root@test 17: 18>insert into test_enum_set values(‘h’, ‘男’, ‘唱歌,运动’);
Query OK, 1 row affected (0.01 sec)
root@test 17: 21>insert into test_enum_set values(‘l’, ‘女’, ‘阅读,运动’);
Query OK, 1 row affected (0.01 sec)
root@test 17: 22>insert into test_enum_set values(‘z’, ‘女’, ‘运动’);
Query OK, 1 row affected (0.00 sec)
root@test 17: 22>insert into test_enum_set values(‘f’, ‘男’, ‘阅读’);
Query OK, 1 row affected (0.03 sec)

查询数据

root@test 17: 22>select * from test_enum_set;
+-----------+------+---------------+
| name      | sex  | hobby         |
+-----------+------+---------------+
| hh      | 男   | 唱歌,运动     |
| lxy    | 女   | 运动,阅读     |
| zmx    | 女   | 运动          |
| zf      | 男   | 阅读          |
+-----------+------+---------------+
4 rows in set (0.00 sec)

返回所有 hobby 字段中包含 ‘运动’ 的记录

root@test 17: 22>select * from test_enum_set where find_in_set('运动', hobby);
+-----------+------+---------------+
| name      | sex  | hobby         |
+-----------+------+---------------+
| hh      | 男   | 唱歌,运动     |
| lxy     | 女   | 运动,阅读     |
| zmx     | 女   | 运动          |
+-----------+------+---------------+
3 rows in set (0.01 sec)

3.4 常见的约束

约束是附加在字段或表上的规则,用于限制字段的取值行为,确保数据的完整性、一致性和有效性

3.4.1 非空约束(NOT NULL)

该列数据不能为空

root@test 09: 41>create table test_not_null (
-> name varchar(10) not null,
-> age tinyint);
Query OK, 0 rows affected (0.02 sec)

设置 not null 显示为 NO

root@test 09: 42>desc test_not_null;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name  | varchar(10) | NO   |     | NULL    |       |
| age   | tinyint     | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

插入两条数据
一条只给age值,不给name值
一条只给name值,不给age值

root@test 09: 42>insert into test_not_null (name) values(‘sc’);
Query OK, 1 row affected (0.00 sec)
 
root@test 09: 45>insert into test_not_null (age) values(18);
ERROR 1364 (HY000): Field ‘name’ doesn’t have a default value


3.4.2 默认值约束(DEFAULT)

该列数据如果没有给值,使用默认值

root@test 09: 46>create table test_default (
-> name varchar(10),
-> status enum(‘active’, ‘inactive’) default ‘active’
-> );
Query OK, 0 rows affected (0.01 sec)

设置枚举类型的默认值为 active

root@test 09: 50>desc test_default;
+--------+---------------------------+------+-----+---------+-------+
| Field  | Type                      | Null | Key | Default | Extra |
+--------+---------------------------+------+-----+---------+-------+
| name   | varchar(10)               | YES  |     | NULL    |       |
| status | enum('active','inactive') | YES  |     | active  |       |
+--------+---------------------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

插入两条数据

  1. 给name和status都给值 cali, inactive
  2. 只给name值 feng

root@test 09: 50>insert into test_default values (‘cali’, ‘inactive’);
Query OK, 1 row affected (0.01 sec)
 
root@test 09: 54>insert into test_default (name) values (‘feng’);
Query OK, 1 row affected (0.01 sec)

root@test 09: 54>select * from test_default;
+------+----------+
| name | status   |
+------+----------+
| cali | inactive |
| feng | active   |
+------+----------+
2 rows in set (0.00 sec)

3.4.3 唯一约束(UNIQUE)

该列数据的值必须唯一,可以为NULL,NULL可重复,可以多个UNIQUE字段

插入4条数据

  1. 只给age值 => 18
  2. 只给age值 => 19
  3. 给name,age值: wen, 18
  4. 给name,age值: wen, 19

root@test 09: 56>insert into test_unique (age) values(18),(19);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
 
root@test 10: 02>insert into test_unique values(‘wen’, 18),(‘wen’, 19);
ERROR 1062 (23000): Duplicate entry ‘wen’ for key ‘test_unique.name’


3.4.4 主键约束(PRIMARY KEY)

不能为空+唯一约束,一个表只能有一个主键

主键:单个字段,多个字段
作用:

  1. 标识唯一的一条记录
  2. 创建了主键之后 => 自动创建索引 => 提升查询效率
  3. 一般来说,建议每个表都创建一个主键(id =》 1,2,3,4,5)

自增主键 AUTO_INCREMENT

root@test 10: 04>create table test_primary_key(
-> id int auto_increment primary key,
-> name varchar(10)
-> );
Query OK, 0 rows affected (0.01 sec)

插入数据

  1. 插入两条数据 (1, ‘cali’), (1, ‘wen’)
  2. 插入1条数据只给name值(‘cici’)
  3. 插入数据(-10, ‘sc’)
root@test 10: 17>select * from test_primary_key;
+-----+------+
| id  | name |
+-----+------+
| -10 | sc   |
|   1 | cali |
|   2 | cici |
+-----+------+
3 rows in set (0.01 sec)

3.4.5 外键约束(FOREIGN KEY)

用于建立表与表之间的关系

分表的意义:
节省存储空间(减少数据冗余)
提升可维护性

数据分表 -> 外键
优点:数据之间有关联,数据一致性检查,数据完整性

缺点:
外键有一定的性能开销(产生临时表、消耗内存和CPU)
复杂性:进行数据插入和删除时,由于有约束更麻烦

企业:会分表
外键 => 数据库层面解决一些约束问题
* 通常从代码层面解决约束问题,不使用外键

CREATE TABLE 子表名 (

外键字段 类型,
FOREIGN KEY (外键字段)
REFERENCES 主表名(主表关联字段)
ON DELETE 动作 - - 主表记录被删除时的动作
ON UPDATE 动作 - - 主表关联字段被更新时的动作
);

创建表classes

root@test 10: 16>create table classes (
-> class_id varchar(10) primary key,
-> class_teacher varchar(10),
-> class_location varchar(100)
-> );
Query OK, 0 rows affected (0.01 sec)

创建表students

root@test 10: 36>create table students(
-> st_name varchar(10),
-> st_id varchar(10) primary key,
-> st_age tinyint,
-> class_id varchar(10),
-> foreign key (class_id) references classes(class_id)
-> );
Query OK, 0 rows affected (0.01 sec)

主键显示为PRI
外键显示为MUL

root@test 10: 40>desc students;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| st_name  | varchar(10) | YES  |     | NULL    |       |
| st_id    | varchar(10) | NO   | PRI | NULL    |       |
| st_age   | tinyint     | YES  |     | NULL    |       |
| class_id | varchar(10) | YES  | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

违反了外键约束,需先插入父表

root@test 10: 42>insert into students values (‘张三’, ‘sc001’, 19, ‘21110’);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`students`, CONSTRAINT `students_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `classes` (`class_id`))

root@test 10: 42>insert into classes values(‘2110’, ‘cali’, ‘东湖小区’) ;
Query OK, 1 row affected (0.00 sec)
root@test 10: 44>insert into students values (‘张三’, ‘sc001’, 19, ‘2110’);
Query OK, 1 row affected (0.01 sec)

外键动作

  1. 限制动作 restrict : 默认
    当删除数据或更新数据时,由于数据被引用,所以会阻该操作

  2. 级联操作 cascade: 级联删除

CREATE TABLE students (

FOREIGN KEY (class_id) REFERENCES classes(class_id)
ON DELETE CASCADE - - 父表记录删除时,子表记录自动删除
ON UPDATE CASCADE - - 父表ID更新时,子表ID自动更新
);

  1. 设置为空 SET NULL
    主表记录被删除 / 更新时,子表中关联的外键字段被自动设为 NULL。
    注意:子表的外键字段必须允许为 NULL(即定义时没有 NOT NULL 约束)

class_id INT NULL,
FOREIGN KEY (class_id) REFERENCES classes(class_id)
ON DELETE SET NULL - - 班级被删除时,学生的 class_id 设为 NULL
ON UPDATE SET NULL - - 班级ID被修改时,学生的 class_id 设为 NULL

  1. 无动作 NO ACTION
    NO ACTION 是 SQL 标准中的术语,MySQL 中实际行为与 RESTRICT 相同

3.5 复制表结构

  1. create table <表2> like <表1>; : 复制结构不复制数据

root@test 10: 49>create table new_classes like classes;
Query OK, 0 rows affected (0.01 sec)

root@test 10: 53>desc classes;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| class_id       | varchar(10)  | NO   | PRI | NULL    |       |
| class_teacher  | varchar(10)  | YES  |     | NULL    |       |
| class_location | varchar(100) | YES  |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)root@test 10: 53>desc new_classes;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| class_id       | varchar(10)  | NO   | PRI | NULL    |       |
| class_teacher  | varchar(10)  | YES  |     | NULL    |       |
| class_location | varchar(100) | YES  |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)root@test 10: 53>select * from classes;
+----------+---------------+----------------+
| class_id | class_teacher | class_location |
+----------+---------------+----------------+
| 2110     | cali          | 东湖小区       |
+----------+---------------+----------------+
1 row in set (0.00 sec)root@test 10: 53>select * from new_classes;
Empty set (0.00 sec)
  1. create table <表2> as select * from <表1>; : 复制结构和数据

root@test 10: 53>create table new_classes2 as select * from classes;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0


3.6 删除表

DROP TABLE <表名>;

root@test 10: 55>drop table new_classes2;
Query OK, 0 rows affected (0.02 sec)

drop table if exists <表名>; :如果删除的表不存在不会报错

root@test 10: 55>drop table if exists new_classes2 ;
Query OK, 0 rows affected, 1 warning (0.00 sec)


3.7 修改表

ALTER TABLE

1.新增列:
添加到最后

alter table articles add phone char(11);

添加到最前

alter table articles add id int first;

添加到指定位置

alter table articles add email varchar(20) after author;

2.修改列:
修改字段类型和约束

alter table articles modify title varchar(200) not null;
alter table product modify column pid int auto_increment;

修改字段名

alter table articles change phone mobile char(11);

删除字段

alter table articles drop column email;

+------+--------+--------------+---------------------+-------+---------+--------+
| id   | title  | content      | publish             | views | author  | mobile |
+------+--------+--------------+---------------------+-------+---------+--------+
| NULL | title1 | abcedfghijkl | 2025-06-27 17:08:23 |    99 | author1 | NULL   |
+------+--------+--------------+---------------------+-------+---------+--------+

添加约束信息

alter table person add constraint pk_username primary key (username);

修改表名

alter table person rename to person2;


3.8 表数据操作

  • 插入数据
    INSERT INTO TABLE VALUES();

  • 更新数据
    update <表名> set 列名=值,列名=值… where 条件;

update product set price=price*10 where price <=100;

  • 删除数据
    delete from <表名> where 条件;

delete from product where pid=13;
Query OK, 1 row affected (0.01 sec)

  • 清空数据
    delete from <表名>;
    truncate table <表名>;

用delete和truncate清空表有什么区别

  • delete: 删除数据时是一行一行的删除(删除慢) -> 删除操作会产生二进制日志 -> 可以数据恢复 -> 使用了自增下次插入会继续递增

  • truncate: 删除表,重新创建表 -> 数据无法恢复
    速度快


总结

库表管理是 MySQL 操作的基础,核心在于:

  • 库管理:通过CREATE DATABASE、USE、ALTER DATABASE、DROP DATABASE等语句管理数据库的生命周期
  • 表管理:通过CREATE TABLE、ALTER TABLE、DROP TABLE等语句定义和维护数据表的结构,包括字段、数据类型、约束(主键、外键等)
http://www.lryc.cn/news/585233.html

相关文章:

  • 斯坦福 CS336 动手大语言模型 Assignment1 BPE Tokenizer TransformerLM
  • 高速路上的 “阳光哨兵”:分布式光伏监控系统守护能源高效运转
  • 250630课题进展
  • 电力自动化的通信中枢,为何工业交换机越来越重要?
  • C++——构造函数
  • 数据库迁移人大金仓数据库
  • stm32-modbus-rs485程序移植过程
  • 微算法科技基于格密码的量子加密技术,融入LSQb算法的信息隐藏与传输过程中,实现抗量子攻击策略强化
  • 【AI大模型】RAG系统组件:向量数据库(ChromaDB)
  • 新作品:吃啥好呢 - 个性化美食推荐
  • QT跨平台应用程序开发框架(4)—— 常用控件QWidget
  • 【机器学习】保序回归平滑校准算法
  • AI在医疗影像诊断中的应用前景与挑战
  • RabbitMQ 之消息积压
  • Linux进程间通信--命名管道
  • Leaflet面试题及答案(1-20)
  • [面试] 手写题-选择排序
  • 【Springboot】Bean解释
  • 为什么必须掌握Java异常处理机制?——从代码健壮性到面试必考题全解析
  • 结构化数据、非结构化数据区别
  • Web安全 - 基于 SM2/SM4 的前后端国产加解密方案详解
  • 远程登录docker执行shell报错input is not a terminal问题
  • 如何将公式图片转换为公式格式到wps/word里面
  • 红色脉络:一部PLMN在中国的演进史诗 (1G-6G)》第1篇 | 开篇:从蜂窝到星链,PLMN——连接世界的无形之网
  • 线性回归原理推导与应用(十):逻辑回归多分类实战
  • LabVIEW前面板设计--控件/文字遮挡
  • Microsoft Word 中 .doc 和 .docx 的区别
  • 利用BeautifulSoup解析大众点评区域店铺网页
  • LabVIEW远程数电实验平台
  • VIT(视觉Transformer)