Tangwx

Tangwx

博客网站

MySQL資料庫

MySQL#

參考連結:

資料庫 day1—— 初識資料庫 - Eva_J - 博客園 (cnblogs.com) 版本:5.6.44

Django 使用 MySQL 資料庫 - 楊仕航的博客 (yshblog.com) 版本:8.0.11

image-20210727081016044

1 下載和安裝#

mysql 為我們提供開源的安裝在各個操作系統上的安裝包,包括 mac,linux,windows。

mysql 的安裝、啟動和基礎配置 —— linux 版本 - Eva_J - 博客園 (cnblogs.com)

mysql 的安裝、啟動和基礎配置 —— mac 版本 - Eva_J - 博客園 (cnblogs.com)

mysql 的安裝、啟動和基礎配置 —— windows 版本 - Eva_J - 博客園 (cnblogs.com)

windows 下載教程#

第一步:打開網址,https://www.mysql.com,點擊 downloads 之後跳轉到https://www.mysql.com/download

第二步 :跳轉至網址https://dev.mysql.com/downloads/,選擇 Community 選項

第三步 :點擊 MySQL Community Server 進入https://dev.mysql.com/downloads/mysql/頁面,再點擊 5.6 版本的資料庫

第四步:windows 操作系統 點擊 5.6 版本之後會跳轉到https://dev.mysql.com/downloads/mysql/5.6.html#downloads 網址,頁面如下,確認好要下載的版本和操作系統,點擊 Download

第五步:可以不用登錄或者註冊,直接點擊 No thanks,just start my download 就可以下載了。

windows 安裝教程#

解壓#

下載的 zip 文件解壓,將解壓之後的文件夾放到任意目錄下,這個目錄就是 mysql 的安裝目錄。路徑必須全英文不帶空格。我安裝在D:\software\MySql\mysql-5.6.44-winx64下。

配置#

打開目錄,會看到 my-default.ini 配置文件,複製這個配置文件可以重命名為 my.ini 或者 my.cnf

將 my.ini 中的文件拖到 pycharm 中來,因為 pycharm 編碼格式是 utf-8

將文件中的內容刪除,將下列代碼複製粘貼到 my.ini 文件中

[mysql]
# 設置mysql客戶端默認字符集
default-character-set=utf8
[mysqld]
#設置3306端口
port = 3306
# 設置mysql的安裝目錄
basedir=C:\Program Files\mysql-5.6.39-winx64
# 設置mysql資料庫的資料的存放目錄
datadir=C:\Program Files\mysql-5.6.39-winx64\data
# 允許最大連接數
max_connections=200
# 服務端使用的字符集默認為8比特編碼的latin1字符集
character-set-server=utf8
# 創建新表時將使用的默認存儲引擎
default-storage-engine=INNODB

修改這些內容:

# 設置mysql的安裝目錄
basedir=D:\software\MySql\mysql-5.6.44-winx64
# 設置mysql資料庫的資料的存放目錄
datadir=D:\software\MySql\mysql-5.6.44-winx64\data

刪除 my.ini 每行文檔最尾端的多餘空格

配置環境變量#

往系統環境變量 ->path 中新建一個變量,將 bin 目錄添加到新建的環境變量中D:\software\MySql\mysql-5.6.44-winx64\bin再確定保存即可。

安裝 MySQL 服務#

以管理員身份打開 cmd 窗口後,將目錄切換到你解壓文件的 bin 目錄,輸入 mysqld install 回車運行

啟動 MySQL 服務#

以管理員身份在 cmd 中輸入 start mysql

C:\windows\system32>net start mysql
請求的服務已經啟動。

請鍵入 NET HELPMSG 2182 以獲得更多的幫助。

服務啟動成功之後,就可以登錄了,輸入mysql -uroot -p(第一次登錄沒有密碼,直接按回車過)

C:\windows\system32>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, 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>

停止 MySQL 服務net stop mysql

C:\windows\system32>net stop mysql
MySQL 服務正在停止.
MySQL 服務已成功停止。

若要重啟 MySQL 服務,windows 中需要先 stop 再 start,且 MySQL 是開機自啟動項目,開機後會自動 start。

客戶端可以是 python 代碼也可以是一個程序,mysql.exe 是一個客戶端,mysql -u 用戶名 -p 密碼登錄 mysql。

2 MySQL 中的用戶和權限#

在安裝資料庫之後,有一個最高權限用戶 root

MySQL server 端的 ip 用戶名 / 密碼

mysql -h 192.168.xx.xx -uroot -p 密碼

我們的 MySQL 客戶端不僅可以連接本地的資料庫,還可以連接網絡上的某一個資料庫的 server 端

查看當前用戶#

在 MySQL 環境內運行select user();注意這最後的英文分號;

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.01 sec)

給當前用戶添加密碼#

在 MySQL 環境內運行set password = password('密碼');注意這最後的英文分號;如果不輸入分號則會一直顯示 -> 無法退出,直到你輸入;

新版本的 mysql 修改密碼應該用這一條 alter user 'root'@'localhost' identified by '123';

我們這個版本仍然使用set password = password('密碼');

創建用戶賬號#

create user 'name'@'192.168.43.%' identified by '密碼';
C:\windows\system32>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, 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> create user 'name'@'192.168.31.%' identified by '123'
    -> ;
Query OK, 0 rows affected (0.09 sec)

mysql> exit
Bye

遠程連接#

mysql -uname -p123 -h192.168.31.144
mysql -u用戶名 -p密碼 -hip -P端口號
mysql -uwanlx -pwanlx -h139.196.217.70 -P8098
C:\windows\system32>mysql -uname -p123 -h192.168.31.144
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, 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> select user();
+----------------------+
| user()               |
+----------------------+
| name@LAPTOP-URS4B7MF |
+----------------------+
1 row in set (0.00 sec)

mysql>

查看文件夾#

show databases;

創建文件夾#

create database 文件夾名
show grant for '用戶名'@'192.168.31.%'

提升用戶權限#

grant all on name.* to 'name'@'192.168.31.%';
flush privileges;

授權並創建用戶#

grant all on name.* to 'alex'@'%' identified by '123';

創建一個名為 alex 的用戶,密碼為 123,只要和我同一個網段都可以控制 name 文件夾裡的所有內容。實際使用報錯,未解決。

mysql> grand all on name.* to 'alex'@'%';
ERROR 1064 (42000): 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 'grand all on name.* to 'alex'@'%'' at line 1

我所使用的命令:

mysql -uroot -p
mysql -uname -p123 -h192.168.31.144

3 sql 語句#

SQL : 結構化查詢語言 (Structured Query Language) 簡稱 SQL (發音:/ˈes kjuː ˈel/ "S-Q-L"),是一種特殊目的的編程語言,是一種資料庫查詢和程序設計語言,用於存取資料以及查詢、更新和管理關係資料庫系統

  SQL 語言主要用於存取資料、查詢資料、更新資料和管理關係資料庫系統,SQL 語言由 IBM 開發。SQL 語言分為 3 種類型:

  1、DDL 語句 資料庫定義語言: 資料庫、表、視圖、索引、存儲過程,例如 CREATE DROP ALTER

  2、DML 語句 資料庫操縱語言: 插入資料 INSERT、刪除資料 DELETE、更新資料 UPDATE、查詢資料 SELECT

  3、DCL 語句 資料庫控制語言: 例如控制用戶的訪問權限 GRANT、REVOKE

庫 表 資料#

先創建庫,再創建表 DDL 資料庫定義語言

存儲資料,刪除資料,修改資料,查詢資料 DML 資料庫操縱語句

庫操作#

create database 資料庫名;

查詢當前有多少庫:show databases;

查看當前使用的資料庫:select database();

切換到這個資料庫(文件夾)下:use 資料庫名字;

drop database 資料庫的名字 刪庫跑路!👀🤣🏃‍♂️

表操作#

查看當前文件夾中有多少張表show tables;

mysql> show tables;
Empty set (0.06 sec)

mysql> show tables;
+----------------+
| Tables_in_demo |
+----------------+
| student        |
+----------------+
1 row in set (0.00 sec)

創建表create table 表的名字(字段命名 數據類型(長度));

create table student(id int,name char(10));

刪除表drop tables 表名;#

查看表結構desc 表名

mysql> desc student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

操作表中資料#

資料的增加insert into 表名 values (字段1,字段2);#
mysql> insert into student values (2,'zhangsan');
Query OK, 1 row affected (0.01 sec)
資料的查看select * from 表名;#
mysql> select * from student;
+------+----------+
| id   | name     |
+------+----------+
|    1 | alex     |
|    2 | zhangsan |
+------+----------+
2 rows in set (0.01 sec)
資料的修改update 表 set 字段名=值;#

若直接update student set name = 'yuan';則會將 name 下所有的資料都修改成 yuan

mysql> update student set name = 'wusir'where id=2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student;
+------+-------+
| id   | name  |
+------+-------+
|    1 | alex  |
|    2 | wusir |
+------+-------+
2 rows in set (0.00 sec)
資料的刪除delete from 表名字;#

若直接執行上述,則會把整個表刪除

mysql> delete from student where id=1;
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+------+-------+
| id   | name  |
+------+-------+
|    2 | wusir |
+------+-------+
1 row in set (0.00 sec)

4 表操作#

存儲引擎#

mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

mysql 中的存儲引擎

表結構和表資料是分開存儲的。

存儲方式1:MyISAM MySQL5.5及以下版本默認存儲方式

表結構、表資料、索引

支持表級鎖 不支持事務、不支持行級鎖、不支持外鍵

存儲方式2: InnoDB MySQL5.6及以上默認存儲方式

	`表結構、表資料 `

支持事務、行級鎖、外鍵 ,也支持表級鎖

​ 行級鎖:

存儲方式3:MEMORY 內存

表結構

優勢:增刪改查都很快

劣勢:重啟資料消失、容量有限

查看相關配置#

mysql> show variables like '%engine%';
+-----------------------------------------+---------------+
| Variable_name                           | Value         |
+-----------------------------------------+---------------+
| default_storage_engine                  | InnoDB        |
| default_tmp_storage_engine              | InnoDB        |
| disabled_storage_engines                |               |
| internal_tmp_mem_storage_engine         | TempTable     |
| secondary_engine_cost_threshold         | 100000.000000 |
| show_create_table_skip_secondary_engine | OFF           |
| use_secondary_engine                    | ON            |
+-----------------------------------------+---------------+
7 rows in set, 1 warning (0.00 sec)

創建表create table t1 (id int,name char(10));;換成\G可以格式整理

查看表結構show create table 表名; 能看到和這張表相關的所有信息

desc 表名; describe 表名;兩張方式查看表結構都是一樣的,前者是簡寫,但這兩種方式都只能查看表的字段基礎信息。

創建表時同時指定存儲引擎create table t2 (id int,name char(10)) engine=myisam;

mysql> create table t2 (id int,name char(10)) engine=myisam;
Query OK, 0 rows affected (0.01 sec)

mysql> show create table t2\G
*************************** 1. row ***************************
       Table: t2
Create Table: CREATE TABLE `t2` (
  `id` int DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| demo               |
| information_schema |
| mysql              |
| name               |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.02 sec)

mysql> create database demo_1;
Query OK, 1 row affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| demo               |
| demo_1             |
| information_schema |
| mysql              |
| name               |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)

mysql> use demo_1
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| demo_1     |
+------------+
1 row in set (0.00 sec)

mysql> create table t1 (id int,name char(10))
    -> ;
Query OK, 0 rows affected (0.07 sec)

mysql> show create table t1;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                   |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| t1    | CREATE TABLE `t1` (
  `id` int DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> describe t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql>

索引 - 資料庫目錄#

創建表#

create table 表名(字段1 類型);

MySQL 基礎數據類型#

數值類型#

MySQL 支持所有標準 SQL 數值數據類型。

這些類型包括嚴格數值數據類型 (INTEGER、SMALLINT、DECIMAL 和 NUMERIC),以及近似數值數據類型 (FLOAT、REAL 和 DOUBLE PRECISION)。

關鍵字 INT 是 INTEGER 的同義詞,關鍵字 DEC 是 DECIMAL 的同義詞。

MySQL 支持的整數類型有 TINYINT、MEDIUMINT 和 BIGINT。下面的表顯示了需要的每個整數類型的存儲和範圍。

對於小數的表示,MYSQL 分為兩種方式:浮點數和定點數。浮點數包括 float (單精度) 和 double (雙精度), 而定點數只有 decimal 一種,在 mysql 中以字符串的形式存放,比浮點數更精確,適合用來表示貨幣等精度高的數據。

BIT 數據類型保存位字段值,並且支持 MyISAM、MEMORY、InnoDB 和 BDB 表。

類型大小範圍(有符號)範圍(無符號)unsigned 約束用途
TINYINT1 字節(-128,127)(0,255)小整數值
SMALLINT2 字節(-32 768,32 767)(0,65 535)大整數值
MEDIUMINT3 字節(-8 388 608,8 388 607)(0,16 777 215)大整數值
INT 或 INTEGER4 字節(-2 147 483 648,2 147 483 647)(0,4 294 967 295)大整數值
BIGINT8 字節(-9 233 372 036 854 775 808,9 223 372 036 854 775 807)(0,18 446 744 073 709 551 615)極大整數值
FLOAT4 字節 float (255,30)(-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38)0,(1.175 494 351 E-38,3.402 823 466 E+38)單精度 浮點數值
DOUBLE8 字節 double (255,30)(-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)雙精度 浮點數值
DECIMAL對 DECIMAL (M,D) ,如果 M>D,為 M+2 否則為 D+2double (65,30)依賴於 M 和 D 的值依賴於 M 和 D 的值小數值

int 默認是有符號的,他能表示的範圍不被寬度約束。

decimal 存儲十分精準,如果不指定則默認(10,0),如果要指定則最多存(25,30)總共存 65 位,其中小數點前存 25 位,小數點後最多存 30 位

日期時間類型#

表示時間值的日期和時間類型為 DATETIME、DATE、TIMESTAMP、TIME 和 YEAR。

每個時間類型有一個有效值範圍和一個 "零" 值,當指定不合法的 MySQL 不能表示的值時使用 "零" 值。

TIMESTAMP 類型有專有的自動更新特性,將在後面描述。

類型大小 (字節)範圍格式用途
DATE31000-01-01/9999-12-31YYYY-MM-DD年月日
TIME3'-838:59:59'/'838:59:59'HH:MM時分秒
YEAR11901/2155YYYY年份值
DATETIME81000-01-01 00:00:00/9999-12-31 23:59:59YYYY-MM-DD HH:MM年月日時分秒
TIMESTAMP41970-01-01 00:00:00/2038 結束時間是第 2147483647 秒,北京時間 2038-1-19 11:14:07,格林尼治時間 2038 年 1 月 19 日 凌晨 03:14:07YYYYMMDD HHMMSS混合日期和時間值,時間戳
mysql> create table t4 (d date,t time,dt datetime);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t4;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| d     | date     | YES  |     | NULL    |       |
| t     | time     | YES  |     | NULL    |       |
| dt    | datetime | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> insert into t4 values (now(),now(),now());
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from t4;
+------------+----------+---------------------+
| d          | t        | dt                  |
+------------+----------+---------------------+
| 2018-09-21 | 14:51:51 | 2018-09-21 14:51:51 |
+------------+----------+---------------------+
1 row in set (0.00 sec)

mysql> insert into t4 values (null,null,null);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t4;
+------------+----------+---------------------+
| d          | t        | dt                  |
+------------+----------+---------------------+
| 2018-09-21 | 14:51:51 | 2018-09-21 14:51:51 |
| NULL       | NULL     | NULL                |
+------------+----------+---------------------+
2 rows in set (0.00 sec)

date/time/datetime示例
mysql> create table t5 (id1 timestamp);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t5;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| id1   | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
1 row in set (0.00 sec)

# 插入資料null,會自動插入當前時間的時間
mysql> insert into t5 values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+---------------------+
| id1                 |
+---------------------+
| 2018-09-21 14:56:50 |
+---------------------+
1 row in set (0.00 sec)

#添加一列 默認值是'0000-00-00 00:00:00'
mysql> alter table t5 add id2 timestamp;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table t5 \G;
*************************** 1. row ***************************
       Table: t5
Create Table: CREATE TABLE `t5` (
  `id1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id2` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

# 手動修改新的列默認值為當前時間
mysql> alter table t5 modify id2 timestamp default current_timestamp;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table t5 \G;
*************************** 1. row ***************************
       Table: t5
Create Table: CREATE TABLE `t5` (
  `id1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id2` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> insert into t5 values (null,null);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t5;
+---------------------+---------------------+
| id1                 | id2                 |
+---------------------+---------------------+
| 2018-09-21 14:56:50 | 0000-00-00 00:00:00 |
| 2018-09-21 14:59:31 | 2018-09-21 14:59:31 |
+---------------------+---------------------+
2 rows in set (0.00 sec)

timestamp示例
mysql> create table t6 (t1 timestamp);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t6;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| t1    | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
1 row in set (0.01 sec)

mysql> insert into t6 values (19700101080001);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t6;
+---------------------+
| t1                  |
+---------------------+
| 1970-01-01 08:00:01 |
+---------------------+
1 row in set (0.00 sec)
# timestamp時間的下限是19700101080001
mysql> insert into t6 values (19700101080000);
ERROR 1292 (22007): Incorrect datetime value: '19700101080000' for column 't1' at row 1

mysql> insert into t6 values ('2038-01-19 11:14:07');
Query OK, 1 row affected (0.00 sec)
# timestamp時間的上限是2038-01-19 11:14:07
mysql> insert into t6 values ('2038-01-19 11:14:08');
ERROR 1292 (22007): Incorrect datetime value: '2038-01-19 11:14:08' for column 't1' at row 1
mysql> 

timestamp示例2
mysql> create table t7 (y year);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into t7 values (2018);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t7;
+------+
| y    |
+------+
| 2018 |
+------+
1 row in set (0.00 sec)

year示例
mysql> create table t8 (dt datetime);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t8 values ('2018-9-26 12:20:10');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t8 values ('2018/9/26 12+20+10');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t8 values ('20180926122010');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t8 values (20180926122010);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t8;
+---------------------+
| dt                  |
+---------------------+
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
+---------------------+
4 rows in set (0.00 sec)

datetime示例
字符串類型#

字符串類型指 CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT、ENUM 和 SET。該節描述了這些類型如何工作以及如何在查詢中使用這些類型。

類型大小用途
CHAR0-255 字節定長字符串
VARCHAR0-65535 字節變長字符串
TINYBLOB0-255 字節不超過 255 個字符的二進制字符串
TINYTEXT0-255 字節短文本字符串
BLOB0-65 535 字節二進制形式的長文本數據
TEXT0-65 535 字節長文本數據
MEDIUMBLOB0-16 777 215 字節二進制形式的中等長度文本數據
MEDIUMTEXT0-16 777 215 字節中等長度文本數據
LONGBLOB0-4 294 967 295 字節二進制形式的極大文本數據
LONGTEXT0-4 294 967 295 字節極大文本數據

CHAR 和 VARCHAR 類型類似,但它們保存和檢索的方式不同。它們的最大長度和是否尾部空格被保留等方面也不同。在存儲或檢索過程中不進行大小寫轉換。

CHAR 列的長度固定為創建表是聲明的長度,範圍 (0-255); 而 VARCHAR 的值是可變長字符串範圍 (0-65535)。

mysql> create table t9 (v varchar(4),c char(4));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t9 values ('ab  ','ab  ');
Query OK, 1 row affected (0.00 sec)

# 在檢索的時候char數據類型會去掉空格
mysql> select * from t9;
+------+------+
| v    | c    |
+------+------+
| ab   | ab   |
+------+------+
1 row in set (0.00 sec)

# 來看看對查詢結果計算的長度
mysql> select length(v),length(c) from t9;
+-----------+-----------+
| length(v) | length(c) |
+-----------+-----------+
|         4 |         2 |
+-----------+-----------+
1 row in set (0.00 sec)

# 給結果拼上個加號會更清楚
mysql> select concat(v,'+'),concat(c,'+') from t9;
+---------------+---------------+
| concat(v,'+') | concat(c,'+') |
+---------------+---------------+
| ab  +         | ab+           |
+---------------+---------------+
1 row in set (0.00 sec)

# 當存儲的長度超出定義的長度,會截斷
mysql> insert into t9 values ('abcd  ','abcd  ');
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from t9;
+------+------+
| v    | c    |
+------+------+
| ab   | ab   |
| abcd | abcd |
+------+------+
2 rows in set (0.00 sec)

char/varchar示例

BINARY 和 VARBINARY 類似於 CHAR 和 VARCHAR,不同的是它們包含二進制字符串而不要非二進制字符串。也就是說,它們包含字節字符串而不是字符字符串。這說明它們沒有字符集,並且排序和比較基於列值字節的數值值。

BLOB 是一個二進制大對象,可以容納可變數量的數據。有 4 種 BLOB 類型:TINYBLOB、BLOB、MEDIUMBLOB 和 LONGBLOB。它們區別在於可容納存儲範圍不同。

有 4 種 TEXT 類型:TINYTEXT、TEXT、MEDIUMTEXT 和 LONGTEXT。對應的這 4 種 BLOB 類型,可存儲的最大長度不同,可根據實際情況選擇。

ENUM 和 SET 類型#

ENUM 中文名稱叫枚舉類型,它的值範圍需要在創建表時通過枚舉方式顯示。ENUM只允許從值集合中選取單個值,而不能一次取多個值

SET 和 ENUM 非常相似,也是個字符串對象,裡面可以包含 0-64 個成員。根據成員的不同,存儲上也有所不同。set 類型可以允許值集合中任意選擇 1 或多個元素進行組合。對超出範圍的內容將不允許注入,而對重複的值將進行自動去重。

類型大小用途
ENUM對 1-255 個成員的枚舉需要 1 個字節存儲;對於 255-65535 個成員,需要 2 個字節存儲;最多允許 65535 個成員。單選:選擇性別
SET1-8 個成員的集合,占 1 個字節 9-16 個成員的集合,占 2 個字節 17-24 個成員的集合,占 3 個字節 25-32 個成員的集合,占 4 個字節 33-64 個成員的集合,占 8 個字節多選:興趣愛好

set/enum 示例

mysql> create table t10 (name char(20),gender enum('female','male'));
Query OK, 0 rows affected (0.01 sec)

# 選擇enum('female','male')中的一項作為gender的值,可以正常插入
mysql> insert into t10 values ('nezha','male');
Query OK, 1 row affected (0.00 sec)

# 不能同時插入'male,female'兩個值,也不能插入不屬於'male,female'的值
mysql> insert into t10 values ('nezha','male,female');
ERROR 1265 (01000): Data truncated for column 'gender' at row 1

mysql> create table t11 (name char(20),hobby set('抽煙','喝酒','燙頭','翻車'));
Query OK, 0 rows affected (0.01 sec)

# 可以任意選擇set('抽煙','喝酒','燙頭','翻車')中的項,並自帶去重功能
mysql> insert into t11 values ('yuan','燙頭,喝酒,燙頭');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t11;
+------+---------------+
| name | hobby        |
+------+---------------+
| yuan | 喝酒,燙頭     |
+------+---------------+
1 row in set (0.00 sec)

# 不能選擇不屬於set('抽煙','喝酒','燙頭','翻車')中的項,
mysql> insert into t11 values ('alex','燙頭,翻車,看妹子');
ERROR 1265 (01000): Data truncated for column 'hobby' at row 1

表的約束#

設置某一個數字為無符號unsigned

約束某一個字段不能為空not null

給某個字段設置默認值default

設置某個字段不能重複unique

設置某個 int 類型的字段自動增加auto_increment

設置某個字段非空且不能重複primary key

外鍵foreign key

聯合唯一#
create table t4(
    id int,
    ip char(15),
    server char(10),
    port int,
    unique(ip,port)
);
mysql> create table t4(
    ->     id int,
    ->     ip char(15),
    ->     server char(10),
    ->     port int,
    ->     unique(ip,port)
    -> );
Query OK, 0 rows affected (0.12 sec)

mysql> desc t4;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int      | YES  |     | NULL    |       |
| ip     | char(15) | YES  | MUL | NULL    |       |
| server | char(10) | YES  |     | NULL    |       |
| port   | int      | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql> show create table t4;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                               |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t4    | CREATE TABLE `t4` (
  `id` int DEFAULT NULL,
  `ip` char(15) DEFAULT NULL,
  `server` char(10) DEFAULT NULL,
  `port` int DEFAULT NULL,
  UNIQUE KEY `ip` (`ip`,`port`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql> insert into t4 values(1,'192.168.12.87','mysql',3306);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t4 values(2,'192.168.12.87','kugou',8000);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t4 values(3,'192.168.12.36','mysql',3306);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t4 values(4,'192.168.12.36','mysql',3306);
ERROR 1062 (23000): Duplicate entry '192.168.12.36-3306' for key 't4.ip'
mysql>
自增auto_increment#

自增字段 必須是數字 且 必須是唯一的 自帶非空效果

create table t5(
    id int unique auto_increment,
    username char(10),
    password char(18)
);
mysql> create table t5(
    ->     id int unique auto_increment,
    ->     username char(10),
    ->     password char(18)
    -> );
Query OK, 0 rows affected (0.07 sec)

mysql> desc t5;
+----------+----------+------+-----+---------+----------------+
| Field    | Type     | Null | Key | Default | Extra          |
+----------+----------+------+-----+---------+----------------+
| id       | int      | NO   | PRI | NULL    | auto_increment |
| username | char(10) | YES  |     | NULL    |                |
| password | char(18) | YES  |     | NULL    |                |
+----------+----------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | alex     | alex3345 |
|  2 | alex     | alex3345 |
|  3 | alex     | alex3345 |
+----+----------+----------+
3 rows in set (0.00 sec)

mysql>show create table t5;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                 |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t5    | CREATE TABLE `t5` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` char(10) DEFAULT NULL,
  `password` char(18) DEFAULT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>
主鍵primary key#

一張表只能有一個主鍵

一張表可以沒有主鍵,但每張表最好設置一個主鍵

約束這個字段 非空(not null)且唯一(unique)

create table t6(
id int not null unique,
name char(12) not null unique
);
mysql> create table t6(
    -> id int not null unique,
    -> name char(12) not null unique
    -> );
Query OK, 0 rows affected (0.03 sec)
mysql> desc t6;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(12) | NO   | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

你指定的第一個非空且唯一的字段會被定義成主鍵

create table t7(
    id int primary key,
    name char(12) not null unique
);
mysql> create table t7(
    ->     id int primary key,
    ->     name char(12) not null unique
    -> );
Query OK, 0 rows affected (0.08 sec)

mysql> desc t7;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(12) | NO   | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)

直接指定 primary key 默認 非空且唯一

聯合主鍵#
create table t8(
    id int,
    ip char(15),
    server char(10),
    port int,
    primary key(ip,port)
);
外鍵foreign key涉及到兩張表#

員工表

id age gender salary hire_date postid

部門表

postname postid post_comment post_phone

mysql> create table post(
    -> postid int primary key,
    -> postname char(10) not null unique,
    -> comment varchar(255),
    -> phone_num char(11)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> create table staff(
    -> id int primary key auto_increment,
    -> age int,
    -> gender enum('male','female'),
    -> salary float(8,2),
    -> hire_date date,
    -> post_id int,
    -> foreign key(post_id) references post(postid)
    -> );
Query OK, 0 rows affected, 1 warning (0.04 sec)

mysql> desc staff;
+-----------+-----------------------+------+-----+---------+----------------+
| Field     | Type                  | Null | Key | Default | Extra          |
+-----------+-----------------------+------+-----+---------+----------------+
| id        | int                   | NO   | PRI | NULL    | auto_increment |
| age       | int                   | YES  |     | NULL    |                |
| gender    | enum('male','female') | YES  |     | NULL    |                |
| salary    | float(8,2)            | YES  |     | NULL    |                |
| hire_date | date                  | YES  |     | NULL    |                |
| post_id   | int                   | YES  | MUL | NULL    |                |
+-----------+-----------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)

mysql> desc post;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| postid    | int          | NO   | PRI | NULL    |       |
| postname  | char(10)     | NO   | UNI | NULL    |       |
| comment   | varchar(255) | YES  |     | NULL    |       |
| phone_num | char(11)     | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> show create table staff;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| staff | CREATE TABLE `staff` (
  `id` int NOT NULL AUTO_INCREMENT,
  `age` int DEFAULT NULL,
  `gender` enum('male','female') DEFAULT NULL,
  `salary` float(8,2) DEFAULT NULL,
  `hire_date` date DEFAULT NULL,
  `post_id` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `post_id` (`post_id`),
  CONSTRAINT `staff_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `post` (`postid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> insert into post values(1 ,'python部門','不錯的團隊','01066666666');
Query OK, 1 row affected (0.01 sec)

mysql> insert into staff values(1 ,80,'male',100000,20101010101010,1);
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql>

外鍵至少關聯一個主鍵,注意:先創建被關聯的表再創建外鍵表,例如上方先創建部門表再創建員工表。

级联刪除和级联更新on update cascade on delete cascade#
mysql> create table staff2(
    -> id int primary key auto_increment,
    -> age int,
    -> gender enum('male','female'),
    -> salary float(8,2),
    -> hire_date date,
    -> post_id int,
    -> foreign key(post_id) references post(postid) on update cascade on delete cascade
    -> );

on delete (了解)

. cascade方式
在父表上update/delete記錄時,同步update/delete掉子表的匹配記錄 

   . set null方式
在父表上update/delete記錄時,將子表上匹配記錄的列設為null
要注意子表的外鍵列不能為not null  

   . No action方式
如果子表中有匹配的記錄,則不允許對父表對應候選鍵進行update/delete操作  

   . Restrict方式
同no action, 都是立即檢查外鍵約束

   . Set default方式
父表有變更時,子表將外鍵列設置成一個默認的值 但Innodb不能識別

修改表#

語法:

  1. 修改表名
    ALTER TABLE 表名
    RENAME 新表名;

  2. 增加字段
    ALTER TABLE 表名
    ADD 字段名 數據類型 [完整性約束條件…],
    ADD 字段名 數據類型 [完整性約束條件…];

  3. 刪除字段
    ALTER TABLE 表名
    DROP 字段名;

  4. 修改字段
    ALTER TABLE 表名
    MODIFY 字段名 數據類型 [完整性約束條件…];
    ALTER TABLE 表名
    CHANGE 舊字段名 新字段名 舊數據類型 [完整性約束條件…];
    ALTER TABLE 表名
    CHANGE 舊字段名 新字段名 新數據類型 [完整性約束條件…];

5. 修改字段排列順序 / 在增加的時候指定字段位置
ALTER TABLE 表名
ADD 字段名 數據類型 [完整性約束條件…] FIRST;
ALTER TABLE 表名
ADD 字段名 數據類型 [完整性約束條件…] AFTER 字段名;
ALTER TABLE 表名
CHANGE 字段名 舊字段名 新字段名 新數據類型 [完整性約束條件…] FIRST;
ALTER TABLE 表名
MODIFY 字段名 數據類型 [完整性約束條件…] AFTER 字段名;

表關係#

兩張表之間的關係

多對一

=====================多對一=====================
create table press(
id int primary key auto_increment,
name varchar(20)
);

create table book(
id int primary key auto_increment,
name varchar(20),
press_id int not null,
foreign key(press_id) references press(id)
on delete cascade
on update cascade
);


insert into press(name) values
('北京工業地雷出版社'),
('人民音樂不好聽出版社'),
('知識產權沒有用出版社')
;

insert into book(name,press_id) values
('九陽神功',1),
('九陰真經',2),
('九陰白骨爪',2),
('獨孤九劍',3),
('降龍十巴掌',2),
('葵花宝典',3)
;

sql示例

一對一

create table customer(
    -> id int primary key auto_increment,
    -> name varchar(20) not null,
    -> qq varchar(10) not null,
    -> phone char(16) not null
    -> );

create table student(
    -> id int primary key auto_increment,
    -> class_name varchar(20) not null,
    -> customer_id int unique, #該字段一定要是唯一的
    -> foreign key(customer_id) references customer(id) #外鍵的字段一定要保證unique
    -> on delete cascade
    -> );

#增加客戶
mysql> insert into customer(name,qq,phone) values
    -> ('韓蕾','31811231',13811341220),
    -> ('楊瀾','123123123',15213146809),
    -> ('翁惠天','283818181',1867141331),
    -> ('楊宗河','283818181',1851143312),
    -> ('袁承明','888818181',1861243314),
    -> ('袁清','112312312',18811431230)

mysql> #增加學生
mysql> insert into student(class_name,customer_id) values
    -> ('脫產1班',3),
    -> ('周末1期',4),
    -> ('周末1期',5)
    -> ;
sql示例

多對多

=====================多對多=====================
create table author(
id int primary key auto_increment,
name varchar(20)
);


#這張表就存放作者表與書表的關係,即查詢二者的關係查這表就可以了
create table author2book(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key(author_id) references author(id)
on delete cascade
on update cascade,
constraint fk_book foreign key(book_id) references book(id)
on delete cascade
on update cascade,
primary key(author_id,book_id)
);


#插入四個作者,id依次排開
insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');

#每個作者與自己的代表作如下
egon: 
九陽神功
九陰真經
九陰白骨爪
獨孤九劍
降龍十巴掌
葵花宝典
alex: 
九陽神功
葵花宝典
yuanhao:
獨孤九劍
降龍十巴掌
葵花宝典
wpq:
九陽神功


insert into author2book(author_id,book_id) values
(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1)
;
sql示例

資料操作#

增加insert#

insert into 表名 values (值...);所有的在這個表中的字段都需要按順序填寫在這裡

insert into 表名 (字段名,字段名...) values (值...);所有在字段位置填寫了名字的字段必須和後面的值一一對應

insert into 表名 value (值...);一次性只能寫入一行資料,values 可以一次寫入多行

刪除delete#

delete from 表 where 條件;

修改update#

update 表 set 字段=新的值 where 條件;

查詢select#

select * from 表名; select 字段 from 表名;

去除重複項select distinct 字段 from 表名;

四則運算select 字段*10 from 表名;同時可以重命名四則運算後的名字select 字段*10 as 新名字 from 表名;或者去掉 as 保留空格

where 語句#

比較運算#

> < = >= <= != <> (也表示不等於)

範圍運算#

​ 多選一 in

select * from 表名 where 字段名 in (值1,值2,值3);

​ 在一個模糊的範圍內

​ 在一個數值區間 [a,b] between

select * from 表名 where 字段名 between a and b;

​ 字符串的模糊查詢like

​ 通配符 %匹配任意長度的任意內容

select * from 表名 where 字段名 like '模糊字符%';

​ 通配符 _匹配一個字符長度的任意內容,缺多少位就要加多少個_

select * from 表名 where 字段名 like '模糊字符__';

​ 正則匹配regexp

select * from 表名 where 字段名 regexp '正則表達式';

邏輯運算 - 條件的拼接#

andornot

分組 group by#

select * from 表名 group by 字段;

會把在 group by 後面的這個字段中的每一個不同的項都保留下來,並把這一項的所有值歸為一組

聚合#

count(字段)統計這個字段有多少項select count(*) from 表名;

sum(字段)統計這個字段對應數值的和

avg(字段)統計這個字段對應數值的平均值

min(字段)統計這個字段對應數值的最小值

max(字段)統計這個字段對應數值的最大值

分組聚合#

select count(*) from 表名 group by 字段;

select sum(字段) from 表名 group by 字段;

過濾having#

having 總是和 group by 一起用

select 字段 from 表名 group by 字段名 having 條件;

select post from employee group by post having count(*) > 3;

查詢排序order by#

select * from 表名 order by 字段名;默認從小到大排,默認是 asc 可省略不寫

select * from 表名 order by 字段名 desc;從大到小排

多列排序:select * from 表名 order by 字段名1 asc,字段名2 desc;可以指定第一個字段升序排列,再第一個字段相同的情況下按第二個字段降序排列

限制查詢的記錄數limit#

select * from 表名 order by 字段名 desc limit 取前多少名的值;

分頁操作

select * from 表名 order by 字段名 desc limit 0,5;從 0 開始取,取前 5 個值

select * from 表名 order by 字段名 desc limit 5,5;從 5 開始取,取後面 5 個

limit m,n 等價於 limit n offset m

它們的順序不能變select distinct 需要顯示的列 from 表 where 條件 group by 分組 having 過濾組條件 order by 排序 limit 前n條

正則查詢#

敲錯換行了可用\c退出

操作 Linux 伺服器下的資料:

連接 mysql 資料庫

C:\Users\HP>mysql -uwanlx -pwanlx -h139.196.217.70 -P8098
mysql: [Warning] Using a passwrord on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 29
Server version: 5.5.5-10.6.4-MariaDB MariaDB Server

Copyright (c) 2000, 2021, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| iot                |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
6 rows in set (0.03 sec)

mysql> select database();
+------------+
| database() |
+------------+
| NULL       |
+------------+
1 row in set (0.05 sec)

進入庫

mysql> use iot;
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| iot        |
+------------+
1 row in set (0.05 sec)

查看表

mysql> show tables;
+---------------+
| Tables_in_iot |
+---------------+
| ClassInfo     |
| StuInfo       |
+---------------+
2 rows in set (0.06 sec)

查看表結構

mysql> desc StuInfo;
+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| id      | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name    | varchar(80)      | NO   |     | NULL    |                |
| class   | varchar(80)      | NO   |     | NULL    |                |
| age     | smallint(6)      | YES  |     | NULL    |                |
| address | varchar(256)     | YES  |     | NULL    |                |
+---------+------------------+------+-----+---------+----------------+
5 rows in set (0.03 sec)

查看表內容

mysql> select * from StuInfo;
+----+--------+-----------------------+------+--------------------+
| id | name   | class                 | age  | address            |
+----+--------+-----------------------+------+--------------------+
|  1 | 萬里霞 | 09級自動化2班         |   31 | 江西省新余市分宜縣 |
|  2 | 湯清華 | 17級自動化1班         |   20 | 江西省贛州市       |
|  3 | 張三   | 19級自動化1班         |   21 | 江西省贛州市       |
|  4 | 李四   | 17級自動化1班         |   22 | 江西省贛州市       |
|  5 | 黃石海 | 19級物聯網工程本科1班 |   22 | 江西省九江市       |
|  6 | 賈景旗 | 19級物聯網工程本科2班 |   22 | 山西省運城市       |
|  7 | 嚴淦   | 19級物聯網工程本科2班 |   22 | 江西省贛州市       |
|  8 | 湯汶熙 | 19級自動化1班         |   22 | 江西省贛州市       |
+----+--------+-----------------------+------+--------------------+
8 rows in set (0.08 sec)

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。