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.pswp.cn/bicheng/88586.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/88586.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025Nginx最新版讲解/面试

维护系统多服务器部署&#xff0c;将我们请求代理到各个服务器。代理正向代理&#xff0c;代理对象是我们的客户端&#xff0c;目标对象不知道我们用户。VPN就是典型的正向代理。反向代理&#xff0c;代理对象是服务端&#xff0c;用户不知道服务端具体信息。而这正是Nginx所做…

JAVASCRIPT 前端数据库-V8--仙盟数据库架构-—-—仙盟创梦IDE

老版本 在v1 版本中我们讲述了 基础版的应用 JAVASCRIPT 前端数据库-V1--仙盟数据库架构-—-—仙盟创梦IDE-CSDN博客 接下载我们做一个更复杂的的其他场景 由于&#xff0c;V1查询字段必须 id 接下来我们修改了了代码 JAVASCRIPT 前端数据库-V2--仙盟数据库架构-—-—仙盟创…

UNIX 域套接字实现本地进程间通信

&#x1f680; 使用 UNIX 域套接字 (AF_UNIX) 实现高效进程通信 在 Linux 和其他类 UNIX 系统中&#xff0c;进程间通信 (IPC) 的方法有很多种&#xff0c;例如管道、消息队列、共享内存等。然而&#xff0c;当你的应用程序需要在 同一台机器上的不同进程间进行高效、低延迟的数…

【Axure教程】中继器间图片的传递

中继器在Axure中可以作为图片保存的数据库&#xff0c;在实际系统中&#xff0c;我们经常需要将选择数据库的图片添加到其他图片列表中&#xff0c;所以今天就教大家&#xff0c;怎么在Axure中实现中继器之间的图片传递&#xff0c;包含将一个中继器中的图片列表传递到另一个中…

专题:2025云计算与AI技术研究趋势报告|附200+份报告PDF、原数据表汇总下载

原文链接&#xff1a;https://tecdat.cn/?p42935 关键词&#xff1a;2025, 云计算&#xff0c;AI 技术&#xff0c;市场趋势&#xff0c;深度学习&#xff0c;公有云&#xff0c;研究报告 云计算和 AI 技术正以肉眼可见的速度重塑商业世界。过去十年&#xff0c;全球云服务收…

从代码学习深度强化学习 - PPO PyTorch版

文章目录 前言PPO 算法简介从 TRPO 到 PPOPPO 的两种形式:惩罚与截断代码实践:PPO 解决离散动作空间问题 (CartPole)环境与工具函数定义策略与价值网络PPO 智能体核心实现训练与结果代码实践:PPO 解决连续动作空间问题 (Pendulum)环境准备适用于连续动作的网络PPO 智能体 (连…

PortsWiggerLab: Blind OS command injection with output redirection

实验目的This lab contains a blind OS command injection vulnerability in the feedback function.The application executes a shell command containing the user-supplied details. The output from the command is not returned in the response. However, you can use o…

星云穿越与超光速飞行特效的前端实现原理与实践

文章目录 1,引言2,特效设计思路3,技术原理解析1. 星点的三维分布2. 视角推进与星点运动3. 三维到二维的投影4. 星点的视觉表现5. 色彩与模糊处理4,关键实现流程图5,应用场景与优化建议6,总结1,引言 在现代网页开发中,炫酷的视觉特效不仅能提升用户体验,还能为产品增添…

【Linux】C++项目分层架构:核心三层与关键辅助

C 项目分层架构全指南&#xff1a;核心三层 关键辅助一、核心三层架构 传统的三层架构&#xff08;或三层体系结构&#xff09;是构建健壮系统的基石&#xff0c;包括以下三层&#xff1a; 1. 表现层&#xff08;Presentation Layer&#xff09; 负责展示和输入处理&#xff0…

【机器学习】保序回归平滑校准算法

保序回归平滑校准算法&#xff08;SIR&#xff09;通过分桶合并线性插值解决广告预估偏差问题&#xff0c;核心是保持原始排序下纠偏。具体步骤&#xff1a;1&#xff09;按预估分升序分桶&#xff0c;统计每个分桶的后验CTR&#xff1b;2&#xff09;合并逆序桶重新计算均值&a…

项目开发日记

框架整理学习UIMgr&#xff1a;一、数据结构与算法 1.1 关键数据结构成员变量类型说明m_CtrlsList<PageInfo>当前正在显示的所有 UI 页面m_CachesList<PageInfo>已打开过、但现在不显示的页面&#xff08;缓存池&#xff09; 1.2 算法逻辑查找缓存页面&#xff1a;…

60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门(附 BeagleBone Black 驱动简单解析)

60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门&#xff08;附 BeagleBone Black 及驱动解析&#xff09;一、什么是 OpenVLC&#xff1f; OpenVLC 是由西班牙 IMDEA Networks 研究所推出的开源可见光通信&#xff08;VLC / Li-Fi&#xff09;研究平台。它把硬件、驱动、协议栈…

Python性能优化

Python 以其简洁和易用性著称,但在某些计算密集型或大数据处理场景下,性能可能成为瓶颈。幸运的是,通过一些巧妙的编程技巧,我们可以显著提升Python代码的执行效率。本文将介绍8个实用的性能优化技巧,帮助你编写更快、更高效的Python代码。   一、优化前的黄金法则:先测…

easyui碰到想要去除顶部栏按钮边框

只需要加上 plain"true"<a href"javascript:void(0)" class"easyui-linkbutton" iconCls"icon-add" plain"true"onclick"newCheck()">新增</a>

C++字符串详解:原理、操作及力扣算法实战

一、C字符串简介在C中&#xff0c;字符串的处理方式主要有两种&#xff1a;字符数组&#xff08;C风格字符串&#xff09;和std::string类。虽然字符数组是C语言遗留的底层实现方式&#xff0c;但现代C更推荐使用std::string类&#xff0c;其封装了复杂的操作逻辑&#xff0c;提…

CMU15445-2024fall-project1踩坑经历

p1目录&#xff1a;lRU\_K替换策略LRULRU\_K大体思路SetEvictableRecordAccessSizeEvictRemoveDisk SchedulerBufferPoolNewPageDeletePageFlashPage/FlashAllPageCheckReadPage/CheckWritePagePageGuard并发设计主逻辑感谢CMU的教授们给我们分享了如此精彩的一门课程&#xff…

【C语言进阶】带你由浅入深了解指针【第四期】:数组指针的应用、介绍函数指针

前言上一期讲了数组指针的原理&#xff0c;这一期接着上一期讲述数组指针的应用以及数组参数、函数参数。首先看下面的代码进行上一期内容的复习&#xff0c;pc应该是什么类型&#xff1f;char* arr[5] {0}; xxx pc &arr;分析&#xff1a;①首先判断arr是一个数组&#x…

在HTML中CSS三种使用方式

一、行内样式在标签<>中输入style "属性&#xff1a;属性值;"。(中等使用频率)不利于CSS样式的复用&#xff1b;违背了CSS内容和样式分离的设计理念&#xff0c;后期难以维护。<p style"color: red">这是div中的p元素</p>二、内部样式在…

汽车功能安全-软件单元验证 (Software Unit Verification)【用例导出方法、输出物】8

文章目录1 软件单元验证用例导出方法2 测试用例完整性度量标准3 验证环境要求4 软件单元验证的工作产品1 软件单元验证用例导出方法 为确保软件单元测试的测试案例规范符合9.4.2要求&#xff0c;应通过表8所列方法开发测试用例。 表8 软件单元测试用例的得出方法&#xff1a; …

MySQL内置函数(8)

文章目录前言一、日期函数二、字符串函数三、数学函数四、其它函数总结前言 其实在之前的几篇中我们也用到了内置函数&#xff0c;现在我们再来系统学习一下它&#xff01; 一、日期函数 函数名称描述current_date()获取当前日期current_time()获取当前时间current_timestamp(…