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~255SMALLINT
2字節MEDIUMINT
3字節INT
4字節BIGINT
8字節
屬性
TYPE(n)
=> 顯示寬度 n=5ZEROFILL
=> 零填充 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-65535TINYTEXT
小文本 0-255MEDIUMTEXT
中等文本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:sstimestamp
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)
插入兩條數據
- 給name和status都給值 cali, inactive
- 只給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條數據
- 只給age值 => 18
- 只給age值 => 19
- 給name,age值: wen, 18
- 給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)
不能為空+唯一約束,一個表只能有一個主鍵
主鍵:單個字段,多個字段
作用:
- 標識唯一的一條記錄
- 創建了主鍵之后 => 自動創建索引 => 提升查詢效率
- 一般來說,建議每個表都創建一個主鍵(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, ‘cali’), (1, ‘wen’)
- 插入1條數據只給name值(‘cici’)
- 插入數據(-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)
外鍵動作
-
限制動作 restrict : 默認
當刪除數據或更新數據時,由于數據被引用,所以會阻該操作 -
級聯操作 cascade: 級聯刪除
CREATE TABLE students (
…
FOREIGN KEY (class_id) REFERENCES classes(class_id)
ON DELETE CASCADE - - 父表記錄刪除時,子表記錄自動刪除
ON UPDATE CASCADE - - 父表ID更新時,子表ID自動更新
);
- 設置為空 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
- 無動作 NO ACTION
NO ACTION 是 SQL 標準中的術語,MySQL 中實際行為與 RESTRICT 相同
3.5 復制表結構
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)
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
articlesadd
phone char(11);
添加到最前
alter table
articlesadd
id intfirst
;
添加到指定位置
alter table
articlesadd
email varchar(20)after
author;
2.修改列:
修改字段類型和約束
alter table
articlesmodify
title varchar(200) not null;
alter table
productmodify
column pid int auto_increment;
修改字段名
alter table
articleschange
phone mobile char(11);
刪除字段
alter table
articlesdrop column
email;
+------+--------+--------------+---------------------+-------+---------+--------+
| id | title | content | publish | views | author | mobile |
+------+--------+--------------+---------------------+-------+---------+--------+
| NULL | title1 | abcedfghijkl | 2025-06-27 17:08:23 | 99 | author1 | NULL |
+------+--------+--------------+---------------------+-------+---------+--------+
添加約束信息
alter table
personadd constraint
pk_username primary key (username);
修改表名
alter table
personrename
to person2;
3.8 表數據操作
-
插入數據
INSERT INTO
TABLEVALUES()
; -
更新數據
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等語句定義和維護數據表的結構,包括字段、數據類型、約束(主鍵、外鍵等)