MySQL 學習(4)—— MySQL 基礎應用(1)| 8月更文挑戰

這是我參與8月更文挑戰的第4天,活動詳情查看:8月更文挑戰mysql

MySQL 內置的功能

鏈接數據庫

-u
-p
-S
-h
-P
-e
複製代碼

示例:sql

# mysql -S /tmp/mysql.sock
# mysql -uroot -p -hlocalhost -P3306
複製代碼

-e 參數的命令是不進行交互:mysql -uroot -e "show processlist";shell

# mysql -uroot -e "show processlist;"
+----+------+-----------+------+---------+------+----------+------------------+
| Id | User | Host      | db   | Command | Time | State    | Info             |
+----+------+-----------+------+---------+------+----------+------------------+
| 10 | root | localhost | NULL | Query   |    0 | starting | show processlist |
+----+------+-----------+------+---------+------+----------+------------------+
複製代碼

< 用於恢復數據,將外部數據導入到 MySQL 中。數據庫

好比咱們將 t_xz_invite 表的數據導入到 MySQL 中。bash

# mysql -uroot account < t_xz_invite.sq
複製代碼

內置命令

  • help —— 幫助命令微信

    • \c 清除當前輸入,結束上一個命令(control + c)
    • \q 退出 mysql(control + d)(exit)
    • \G 格式化輸出結果
    • source 恢復數據(同 <)

1 SQL 介紹

  • 結構化的查詢語言
  • 關係型數據庫通用的命令
  • 遵循 SQL92 標準(SQL_MODE)

2 SQL 經常使用種類

  • DDL:數據定義語言
  • DCL:數據控制語言
  • DML:數據操做語言
  • DQL:數據查詢語言

3 SQL 引入——數據庫的邏輯結構

  • markdown

    • 庫名
    • 庫屬性:字符集、排序規則
  • post

    • 表名
    • 表屬性:存儲引擎、字符集、排序規則
    • 列屬性:數據類型、約束、其餘屬性
    • 數據行

4 字符集(charset)

至關於 MySQL 的一個密碼本(字符集編碼)。ui

咱們能夠經過 show charset; 命令來查看 MySQL 支持的字符集。編碼

mysql> show charset;
+----------+---------------------------------+---------------------+--------+
| Charset  | Description                     | Default collation   | Maxlen |
+----------+---------------------------------+---------------------+--------+
| big5     | Big5 Traditional Chinese        | big5_chinese_ci     |      2 |
| dec8     | DEC West European               | dec8_swedish_ci     |      1 |
| cp850    | DOS West European               | cp850_general_ci    |      1 |
| hp8      | HP West European                | hp8_english_ci      |      1 |
| koi8r    | KOI8-R Relcom Russian           | koi8r_general_ci    |      1 |
| latin1   | cp1252 West European            | latin1_swedish_ci   |      1 |
| latin2   | ISO 8859-2 Central European     | latin2_general_ci   |      1 |
| swe7     | 7bit Swedish                    | swe7_swedish_ci     |      1 |
| ascii    | US ASCII                        | ascii_general_ci    |      1 |
| ujis     | EUC-JP Japanese                 | ujis_japanese_ci    |      3 |
| sjis     | Shift-JIS Japanese              | sjis_japanese_ci    |      2 |
| hebrew   | ISO 8859-8 Hebrew               | hebrew_general_ci   |      1 |
| tis620   | TIS620 Thai                     | tis620_thai_ci      |      1 |
| euckr    | EUC-KR Korean                   | euckr_korean_ci     |      2 |
| koi8u    | KOI8-U Ukrainian                | koi8u_general_ci    |      1 |
| gb2312   | GB2312 Simplified Chinese       | gb2312_chinese_ci   |      2 |
| greek    | ISO 8859-7 Greek                | greek_general_ci    |      1 |
| cp1250   | Windows Central European        | cp1250_general_ci   |      1 |
| gbk      | GBK Simplified Chinese          | gbk_chinese_ci      |      2 |
| latin5   | ISO 8859-9 Turkish              | latin5_turkish_ci   |      1 |
| armscii8 | ARMSCII-8 Armenian              | armscii8_general_ci |      1 |
| utf8     | UTF-8 Unicode                   | utf8_general_ci     |      3 |
| ucs2     | UCS-2 Unicode                   | ucs2_general_ci     |      2 |
| cp866    | DOS Russian                     | cp866_general_ci    |      1 |
| keybcs2  | DOS Kamenicky Czech-Slovak      | keybcs2_general_ci  |      1 |
| macce    | Mac Central European            | macce_general_ci    |      1 |
| macroman | Mac West European               | macroman_general_ci |      1 |
| cp852    | DOS Central European            | cp852_general_ci    |      1 |
| latin7   | ISO 8859-13 Baltic              | latin7_general_ci   |      1 |
| utf8mb4  | UTF-8 Unicode                   | utf8mb4_general_ci  |      4 |
| cp1251   | Windows Cyrillic                | cp1251_general_ci   |      1 |
| utf16    | UTF-16 Unicode                  | utf16_general_ci    |      4 |
| utf16le  | UTF-16LE Unicode                | utf16le_general_ci  |      4 |
| cp1256   | Windows Arabic                  | cp1256_general_ci   |      1 |
| cp1257   | Windows Baltic                  | cp1257_general_ci   |      1 |
| utf32    | UTF-32 Unicode                  | utf32_general_ci    |      4 |
| binary   | Binary pseudo charset           | binary              |      1 |
| geostd8  | GEOSTD8 Georgian                | geostd8_general_ci  |      1 |
| cp932    | SJIS for Windows Japanese       | cp932_japanese_ci   |      2 |
| eucjpms  | UJIS for Windows Japanese       | eucjpms_japanese_ci |      3 |
| gb18030  | China National Standard GB18030 | gb18030_chinese_ci  |      4 |
+----------+---------------------------------+---------------------+--------+
41 rows in set (0.02 sec)
複製代碼

MySQL5.7 默認的字符集是 latin1,固然,這是一個歷史遺留的問題。

中文在下面幾個字符集中佔得字節:

  • gbk —— 佔 2 個字節
  • utf8 —— 佔 3 個字節
  • utf8mb4 —— 佔 4 個字節(建議使用這個)

注意:utf8mb4 支持 emoji。

5. 排序規則(collation)

咱們使用 show collation; 命令查看排序規則。

注意:排序規則涉及 字符串大小寫敏感 問題。

mysql> show collation;
+--------------------------+----------+-----+---------+----------+---------+
| Collation                | Charset  | Id  | Default | Compiled | Sortlen |
+--------------------------+----------+-----+---------+----------+---------+
| big5_chinese_ci          | big5     |   1 | Yes     | Yes      |       1 |
| big5_bin                 | big5     |  84 |         | Yes      |       1 |
| dec8_swedish_ci          | dec8     |   3 | Yes     | Yes      |       1 |
| dec8_bin                 | dec8     |  69 |         | Yes      |       1 |
| gb18030_unicode_520_ci   | gb18030  | 250 |         | Yes      |       8 |
+--------------------------+----------+-----+---------+----------+---------+
222 rows in set (0.00 sec)
複製代碼

咱們以 utf8mb4 爲例:

| utf8mb4_general_ci       | utf8mb4  |  45 | Yes     | Yes      |       1 |
| utf8mb4_bin              | utf8mb4  |  46 |         | Yes      |       1 |
| utf8mb4_unicode_ci       | utf8mb4  | 224 |         | Yes      |       8 |
| utf8mb4_icelandic_ci     | utf8mb4  | 225 |         | Yes      |       8 |
| utf8mb4_latvian_ci       | utf8mb4  | 226 |         | Yes      |       8 |
| utf8mb4_romanian_ci      | utf8mb4  | 227 |         | Yes      |       8 |
| utf8mb4_slovenian_ci     | utf8mb4  | 228 |         | Yes      |       8 |
| utf8mb4_polish_ci        | utf8mb4  | 229 |         | Yes      |       8 |
| utf8mb4_estonian_ci      | utf8mb4  | 230 |         | Yes      |       8 |
| utf8mb4_spanish_ci       | utf8mb4  | 231 |         | Yes      |       8 |
| utf8mb4_swedish_ci       | utf8mb4  | 232 |         | Yes      |       8 |
| utf8mb4_turkish_ci       | utf8mb4  | 233 |         | Yes      |       8 |
| utf8mb4_czech_ci         | utf8mb4  | 234 |         | Yes      |       8 |
| utf8mb4_danish_ci        | utf8mb4  | 235 |         | Yes      |       8 |
| utf8mb4_lithuanian_ci    | utf8mb4  | 236 |         | Yes      |       8 |
| utf8mb4_slovak_ci        | utf8mb4  | 237 |         | Yes      |       8 |
| utf8mb4_spanish2_ci      | utf8mb4  | 238 |         | Yes      |       8 |
| utf8mb4_roman_ci         | utf8mb4  | 239 |         | Yes      |       8 |
| utf8mb4_persian_ci       | utf8mb4  | 240 |         | Yes      |       8 |
| utf8mb4_esperanto_ci     | utf8mb4  | 241 |         | Yes      |       8 |
| utf8mb4_hungarian_ci     | utf8mb4  | 242 |         | Yes      |       8 |
| utf8mb4_sinhala_ci       | utf8mb4  | 243 |         | Yes      |       8 |
| utf8mb4_german2_ci       | utf8mb4  | 244 |         | Yes      |       8 |
| utf8mb4_croatian_ci      | utf8mb4  | 245 |         | Yes      |       8 |
| utf8mb4_unicode_520_ci   | utf8mb4  | 246 |         | Yes      |       8 |
| utf8mb4_vietnamese_ci    | utf8mb4  | 247 |         | Yes      |       8 |
複製代碼

_ci 結尾的排序規則是大小寫不敏感的,好比 utf8mb4_general_ci,然後面的 Yes 表明這是默認的排序規則。

所以,當咱們須要大小寫敏感的時候,須要修改相應的排序規則。

6. 數據類型介紹

數據類型在 MySQL 中被規劃爲 4 種:

  1. 數字類型
  2. 字符串類型
  3. 時間類型
  4. 二進制類型

6.1 數字類型

  • 整數(主要介紹)
  • 浮點數
類型 說明
整數 tinyint 極小整數類型(0-255),有符號的爲 -128 - 127
整數 smallint 較小整數數據類型(-2^15 到 2^15-1)
整數 mediumint 中型整數數據類型
整數 int 常規(平均)大小的整數數據類型(-2^31 到 2^31-1)
整數 bigint 較大整數數據類型(-2^63 到 2^63-1)
浮點數 float 小型單精度(四個字節)浮點數
浮點數 double 常規雙精度(八個字節)浮點數
定點數 decimal 包含整數部分、小數部分或同時包括兩者的精確值數值
BIT bit 位字段值

2^31=2147483648,所以 int 最多存儲 10 位。

6.2 字符串類型

須要特別注意的是:

  • char

    • 存儲定長字符串類型,好比 char(100),不管你存儲 20 個仍是 50 個,都是佔用 100 個字符長度存儲空間。
    • 在分配的時候,無論字符串長度多長,都當即分配 100 個字符長度的存儲空間,未佔滿的空間使用「空格」填充
  • varchar

    • 存儲變長字符串類型,每次存儲數據以前,都要先判斷一下長度,按需分配磁盤空間。
    • 會單獨申請一個字符串長度的空間存儲字符長度(少於 255,若是超過 255 以上,會佔用兩個存儲空間)
  • enum

    • 枚舉數據類型

char 最多存儲 255 個字符,varchar 最多存儲 65535 個字符(實際上是 65533 個,用兩個來存儲長度)

如何選擇兩種數據類型呢?

  • 少於 255 個字符長度,定長的列值,選擇 char
  • 多於 255 個字符長度,變長的字符串,能夠選擇 varchar

6.3 時間類型

  • datetime

    • 範圍:1000-01-01 00:00:00 至 9999-12-31 23:59:59
  • timestamp

    • 範圍:1970-01-01 00:00:00 至 2038-12-31 23:59:59
    • 能夠根據時區自動變動時間

7. DDL 的應用

7.1 DDL 語句庫的定義

  • 建立數據庫:
mysql> create database account charset utf8mb4 collate utf8mb4_bin;
Query OK, 1 row affected (0.00 sec)
複製代碼
  • 查看數據庫(不屬於 DDL):
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| account            |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
複製代碼
  • 查看數據庫建立語句(不屬於 DDL):
mysql> show create database account;
+----------+-----------------------------------------------------------------------------------------+
| Database | Create Database                                                                         |
+----------+-----------------------------------------------------------------------------------------+
| account  | CREATE DATABASE `account` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin */ |
+----------+-----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
複製代碼
  • 刪除數據庫:
複製代碼
  • 修改數據庫:

    • 修改數據庫字符集(注意:必定是源字符集的超集,好比 utf8 -> utf8mb4):
mysql> create database test;
Query OK, 1 row affected (0.00 sec)

mysql> show create database test;
+----------+-----------------------------------------------------------------+
| Database | Create Database                                                 |
+----------+-----------------------------------------------------------------+
| test     | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-----------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> alter database test charset utf8mb4;
Query OK, 1 row affected (0.00 sec)

mysql> show create database test;
+----------+------------------------------------------------------------------+
| Database | Create Database                                                  |
+----------+------------------------------------------------------------------+
| test     | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ |
+----------+------------------------------------------------------------------+
1 row in set (0.00 sec)
複製代碼
* 修改排序類型同理。
複製代碼

7.2 關於庫定義規範

  1. 庫名使用小寫字符
  2. 庫名不能以數字開頭
  3. 不能是數據庫內部的關鍵字
  4. 必須設置字符集

7.3 DDL —— 表定義

  • 建表
    • 表名
    • 列名
    • 列屬性
      • PRIMARY KEY:主鍵約束,表中只能有一個,非空且惟一;
      • NOT NULL:非空約束,不容許空值;
      • UNIQUE KEY:惟一鍵約束,不容許重複值;
      • DEFAULT:通常配合 NOT NULL 一塊兒使用,默認值;
      • UNSIGNED:無符號,通常配合數字列,非負數;
      • COMMENT:註釋;
    • 表屬性
create table student (
id INT primary key NOT NULL AUTO_INCREMENT COMMENT '學號',
sname VARCHAR(255) NOT NULL COMMENT '姓名',
age TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年齡',
gender ENUM('m','f','n') NOT NULL DEFAULT 'n' COMMENT '性別',
intime DATETIME NOT NULL DEFAULT NOW() COMMENT '入學時間'
) ENGINE InnoDB CHARSET utf8mb4;
複製代碼
  • 建表規範:

    1. 表名小寫字母,不能是數字開頭;
    2. 不能是保留字符,使用和業務有關的表名;
    3. 選擇合適的數據類型及長度;
    4. 每一個列設置 NOT NULL + DEFAULT,對於數字用 0 填充,對於字符串使用有效字符串填充;
    5. 每一個列設置註釋;
    6. 表必須設置存儲引擎和字符集;
    7. 主鍵列儘可能是無關列數字列,最好是自增加;
    8. enum 類型不要保存數字,只能保存字符串類型;
  • 查詢建表信息:

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

mysql> show create table student;
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                                                                                                                                                                                                                           |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| student | CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '學號',
  `sname` varchar(255) NOT NULL COMMENT '姓名',
  `age` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '年齡',
  `gender` enum('m','f','n') NOT NULL DEFAULT 'n' COMMENT '性別',
  `intime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入學時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4             |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
複製代碼
  • 建立一個如出一轍的表:
mysql> create table test like student;
Query OK, 0 rows affected (0.04 sec)
複製代碼
  • 刪除表;
mysql> drop table test;
Query OK, 0 rows affected (0.02 sec)
複製代碼
  • 查看錶字段:
mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(255)        | NO   |     | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| gender | enum('m','f','n')   | NO   |     | n                 |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
+--------+---------------------+------+-----+-------------------+----------------+
5 rows in set (0.00 sec)
複製代碼
  • 添加列:
mysql> alter table student add qq varchar(20) NOT NULL COMMENT 'qq號';
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(255)        | NO   |     | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| gender | enum('m','f','n')   | NO   |     | n                 |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
| qq     | varchar(20)         | NO   |     | NULL              |                |
+--------+---------------------+------+-----+-------------------+----------------+
6 rows in set (0.00 sec)
複製代碼
  • 添加列(在某個列以後):
mysql> alter table student add wechat varchar(60) NOT NULL UNIQUE COMMENT '微信號' after sname;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(255)        | NO   |     | NULL              |                |
| wechat | varchar(60)         | NO   | UNI | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| gender | enum('m','f','n')   | NO   |     | n                 |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
| qq     | varchar(20)         | NO   |     | NULL              |                |
+--------+---------------------+------+-----+-------------------+----------------+
7 rows in set (0.00 sec)
複製代碼
  • 添加列(在某個列以前添加列):
mysql> alter table student add num INT NOT NULL COMMENT '身份證' FIRST;
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| num    | int(11)             | NO   |     | NULL              |                |
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(255)        | NO   |     | NULL              |                |
| wechat | varchar(60)         | NO   | UNI | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| gender | enum('m','f','n')   | NO   |     | n                 |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
| qq     | varchar(20)         | NO   |     | NULL              |                |
+--------+---------------------+------+-----+-------------------+----------------+
8 rows in set (0.00 sec)
複製代碼
  • 刪除列:
mysql> alter table student drop num;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(255)        | NO   |     | NULL              |                |
| wechat | varchar(60)         | NO   | UNI | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| gender | enum('m','f','n')   | NO   |     | n                 |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
| qq     | varchar(20)         | NO   |     | NULL              |                |
+--------+---------------------+------+-----+-------------------+----------------+
7 rows in set (0.01 sec)
複製代碼
  • 修改字段屬性:
mysql> alter table student modify sname varchar(64) NOT NULL COMMENT '姓名';
Query OK, 0 rows affected (0.10 sec)
Records: 0  Duplicates: 0  Warnings: 0
複製代碼
  • 修改字段類型:
mysql> alter table student change gender sex char(4) NOT NULL COMMENT '性別';
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+--------+---------------------+------+-----+-------------------+----------------+
| Field  | Type                | Null | Key | Default           | Extra          |
+--------+---------------------+------+-----+-------------------+----------------+
| id     | int(11)             | NO   | PRI | NULL              | auto_increment |
| sname  | varchar(64)         | NO   |     | NULL              |                |
| wechat | varchar(60)         | NO   | UNI | NULL              |                |
| age    | tinyint(3) unsigned | NO   |     | 0                 |                |
| sex    | char(4)             | NO   |     | NULL              |                |
| intime | datetime            | NO   |     | CURRENT_TIMESTAMP |                |
| qq     | varchar(20)         | NO   |     | NULL              |                |
+--------+---------------------+------+-----+-------------------+----------------+
7 rows in set (0.00 sec)
複製代碼

7.4 DCL

  • grant
  • revoke

7.5 DML

  • insert
-- 插入一行,不帶字段
mysql> insert into student values(1,'關羽',20,'m',now());
Query OK, 1 row affected (0.00 sec)

-- 插入一行,帶字段
mysql> insert into student(sname,age,sex) values ('劉備',21,'m');
Query OK, 1 row affected (0.01 sec)

-- 多行插入
mysql> insert into student(sname,age,sex) values ('趙雲',22,'m'),('黃忠',23,'m');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+--------+-----+-----+---------------------+
| id | sname  | age | sex | intime              |
+----+--------+-----+-----+---------------------+
|  1 | 關羽   |  20 | m   | 2021-01-24 20:21:50 |
|  2 | 劉備   |  21 | m   | 2021-01-24 20:23:23 |
|  3 | 趙雲   |  22 | m   | 2021-01-24 20:24:38 |
|  4 | 黃忠   |  23 | m   | 2021-01-24 20:24:38 |
+----+--------+-----+-----+---------------------+
4 rows in set (0.00 sec)
複製代碼
  • update
  • delete
相關文章
相關標籤/搜索