Linux服務-mysql基礎篇

mysql基礎正則表達式

1. 關係型數據庫介紹

1.1 數據結構模型

數據結構模型主要有:sql

  • 層次模型
  • 網狀結構
  • 關係模型

關係模型又分爲:數據庫

  • 二維關係:row(行),column(列)
  • 數據庫管理系統:DBMS(database manager system)
  • 關係數據庫管理系統(Relational database manager system)

1.2 RDBMS專業名詞

常見的關係型數據庫管理系統express

  • MySQL:MySQL,MariaDB(和MySQL是同源,RHEL7上yum源自帶),Percona-Server
  • PostgreSQL:簡稱爲pgsql
  • Oracle
  • MSSQL

事務:多個操做被看成一個總體對待就稱爲一個事務(整個事務中的全部操做,要麼所有完成,要麼所有不完成,不可能停滯在中間某個環節。事務在執行過程當中發生錯誤,會被回滾(Rollback)到事務開始前的狀態,就像這個事務歷來沒有執行過同樣。)安全

要看一個關係型數據庫是否支持事務,須要看其是否支持並知足ACID測試服務器

ACID:ACID是事務的一個基本標準數據結構

  • A:Automicity,原子性
  • C:Consistency,一致性
  • I:Isolation,隔離性
  • D:Durability,持久性

SQL:Structure Query Language,結構化查詢語言app

約束:constraint,向數據表提供的數據要遵照的限制socket

  • 主鍵約束:一個或多個字段的組合,填入的數據必須能在本表中惟一標識本行。且必須提供數據,不能爲空(NOT NULL)。一個表只能存在一個
  • 唯一鍵約束:一個或多個字段的組合,填入的數據必須能在本表中惟一標識本行。容許爲空(NULL)一個表能夠存在多個
  • 外鍵約束:一個表中的某字段可填入數據取決於另外一個表的主鍵已有的數據
  • 檢查性約束

索引:將表中的一個或多個字段中的數據複製一份另存,而且這些數據須要按特定次序排序存儲

關係運算

  • 選擇:挑選出符合條件的行(部分行)
  • 投影:挑選出須要的字段(通常是列)
  • 鏈接(將兩個表相關聯)

數據抽象方式:

  • 物理層:決定數據的存儲格式,即RDBMS在磁盤上如何組織文件
  • 邏輯層:描述DB存儲什麼數據,以及數據間存在什麼樣的關係
  • 視圖層:描述DB中的部分數據

1.3 關係型數據庫的常見組件

關係型數據庫的常見組件有:

  • 數據庫:database
  • 表:table,由行(row)和列(column)組成
  • 索引:index
  • 視圖:view
  • 用戶:user
  • 權限:privilege
  • 存儲過程:procedure
  • 存儲函數:function
  • 觸發器:trigger
  • 事件調度器:event scheduler

1.4 SQL語句

SQL語句有三種類型:

  • DDL:Data Defination Language,數據定義語言
  • DML:Data Manipulation Language,數據操縱語言
  • DCL:Data Control Language,數據控制語言
SQL語句類型 對應操做
DDL CREATE:建立
DROP:刪除
ALTER:修改
DML INSERT:向表中插入數據
DELETE:刪除表中數據
UPDATE:更新表中數據
SELECT:查詢表中數據
DCL GRANT:受權
REVOKE:移除受權

2. mysql安裝與配置

2.1 mysql安裝

mysql安裝方式有三種:

  • 源代碼:編譯安裝
  • 二進制格式的程序包:展開至特定路徑,並通過簡單配置後便可使用
  • 程序包管理器管理的程序包:
    1.rpm(有兩種,os Vendor,項目官方提供)
    2.deb
//第一步下載mysql5.7的yum源
[root@cwh ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
--2019-04-22 15:04:39--  http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
...
...
2019-04-22 15:04:46 (389 KB/s) - 已保存 「mysql57-community-release-el7-10.noarch.rpm」 [25548/25548])
[root@cwh ~]# ls
aaa  anaconda-ks.cfg  cwh4http.sh  httpd.conf  httpd-vhosts.conf  httppz1.sh  mysql57-community-release-el7-10.noarch.rpm

//第二步安裝下載下來的mysql源
[root@cwh ~]# yum -y install mysql57-community-release-el7-10.noarch.rpm
[root@cwh ~]# ls /etc/yum.repos.d/
7CentOS-Base.repo  mysql-community.repo  mysql-community-source.repo  redhat.repo

//第三步安裝mysql5.7
yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel

2.2 mysql基本配置

//第一步啓動mysql並查看端口是否開啓
[root@cwh ~]# systemctl start mysqld
[root@cwh ~]# ss -antl
State       Recv-Q Send-Q                     Local Address:Port                                    Peer Address:Port              
LISTEN      0      128                                    *:22                                                 *:*                  
LISTEN      0      100                            127.0.0.1:25                                                 *:*                  
LISTEN      0      80                                    :::3306                                              :::*                  
LISTEN      0      128                                   :::22                                                :::*                  
LISTEN      0      100                                  ::1:25                                                :::*                  

//第二步在mysql日誌文件中找出mysql臨時密碼
[root@cwh ~]# cat /var/log/mysqld.log |grep password
2019-04-22T07:40:39.531315Z 1 [Note] A temporary password is generated for root@localhost: xB>aDF_l>4>; 
//最後的xB>aDF_l>4>;爲臨時密碼之後登錄時須要

//第三步使用獲取到的臨時密碼登陸mysql
[root@localhost ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

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登陸密碼
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=1;
Query OK, 0 rows affected (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'cwh123!';
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye

//第五步爲避免mysql自動升級,這裏須要卸載最開始安裝的yum源
[root@localhost ~]# rpm -qa |grep mysql
mysql-community-common-5.7.25-1.el7.x86_64
mysql-community-libs-5.7.25-1.el7.x86_64
mysql-community-libs-compat-5.7.25-1.el7.x86_64
mysql-community-server-5.7.25-1.el7.x86_64
mysql57-community-release-el7-10.noarch
mysql-community-client-5.7.25-1.el7.x86_64
mysql-community-devel-5.7.25-1.el7.x86_64
[root@localhost ~]# yum -y remove mysql57-community-release-el7-10.noarch

3. mysql的程序組成

  • 客戶端
    • mysql:CLI交互式客戶端程序
    • mysql_secure_installation:安全初始化,強烈建議安裝完之後執行此命令
    • mysqldump:mysql備份工具
    • mysqladmin
  • 服務器端
    • mysqld

3.1 mysql工具使用

//語法:mysql [OPTIONS] [database]
//經常使用的OPTIONS:
-uUSERNAME      //指定用戶名,默認爲root
    -hHOST          //指定服務器主機,默認爲localhost,推薦使用ip地址
    -pPASSWORD      //指定用戶的密碼
    -P#             //指定數據庫監聽的端口,這裏的#需用實際的端口號代替,如-P3307
    -V              //查看當前使用的mysql版本
    -e          //不登陸mysql執行sql語句後退出,經常使用於腳本

//查看當前使用的mysql腳本
[root@localhost ~]# mysql -V
mysql  Ver 14.14 Distrib 5.7.25, for Linux (x86_64) using  EditLine wrapper

//本地登陸
[root@cwh ~]# mysql -uroot -pcwh123! -h127.0.0.1
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 13
Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

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>  //此時顯示已經登錄上了

//注意,不推薦直接在命令行裏直接用-pPASSWORD的方式登陸,而是使用-p選項,而後交互式輸入密碼
[root@cwh ~]# mysql -uroot -p -h127.0.0.1
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

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中有哪些數據庫
[root@localhost ~]# mysql -uroot -p -h127.0.0.1 -e 'show databases'
Enter password: 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

3.2 服務器監聽的兩種socket地址

socket類型 說明
ip socket 默認監聽在tcp的3306端口,支持遠程通訊
unix sock 監聽在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock
僅支持本地通訊
server地址只能是:localhost,127.0.0.1

4. mysql數據庫操做

4.1 DDL操做

4.1.1 數據庫操做

//建立數據庫
//語法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';
//建立數據庫chengweihong
[root@localhost ~]# mysql -uroot -p
Enter password: 
mysql>
mysql> create database if not exists chengweihong;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| chengweihong       |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

//刪除數據庫
//語法:DROP DATABASE [IF EXISTS] 'DB_NAME';
//刪除數據庫chengweihong
mysql> drop database if exists chengweihong;
Query OK, 0 rows affected (0.02 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

4.1.2 表操做

//建立表
//語法:CREATE TABLE table_name (col1 datatype 修飾符,col2 datatype 修飾符) ENGINE='存儲引擎類型';
//在數據庫chengweihong裏建立表cwh
//首先建立chengweihong數據庫
mysql> create database chengweihong;
Query OK, 1 row affected (0.01 sec)
//在在數據庫chengweihong中建立表
mysql> create table cwh(id int not null,name varchar(100),age tinyint);
Query OK, 0 rows affected (0.04 sec)
mysql> show tables;
+------------------------+
| Tables_in_chengweihong |
+------------------------+
| cwh                    |
+------------------------+
1 row in set (0.00 sec)
//具體查看錶的內容
mysql> desc cwh;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | varchar(100) | YES  |     | NULL    |       |
| age   | tinyint(4)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

//刪除表
//語法:DROP TABLE [ IF EXISTS ] 'table_name';
//刪除表cwh
mysql> drop table if exists cwh;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
Empty set (0.00 sec)

4.1.3 用戶操做

mysql用戶賬號由兩部分組成,如'USERNAME'@'HOST',表示此USERNAME只能今後HOST上遠程登陸

這裏('USERNAME'@'HOST')的HOST用於限制此用戶可經過哪些主機遠程鏈接mysql程序,其值可爲:

  • IP地址,如:172.16.12.129
  • 通配符
    • %:匹配任意長度的任意字符,經常使用於設置容許從任何主機登陸
    • _:匹配任意單個字符
//數據庫用戶建立
//語法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
//建立數據庫用戶wangqing
mysql> create user cwh@192.168.112.149 identified by 'cwh123!';
Query OK, 0 rows affected (0.01 sec)
//在192.168.112.149上驗證
[root@149 ~]# mysql -ucwh -p -h192.168.112.146
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]>  //由於沒有配置權限因此查看的東西有限,看不到chengweihong的數據庫
MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.01 sec)

//刪除數據庫用戶
//語法:DROP USER 'username'@'host'; 
mysql> drop user cwh@192.168.112.149;
Query OK, 0 rows affected (0.01 sec)
//刪除用戶後在192.168.112.149主機上驗證
[root@149 ~]# mysql -ucwh -p -h192.168.112.146
Enter password: 
ERROR 1130 (HY000): Host '192.168.112.149' is not allowed to connect to this MySQL server
//能夠看出已經沒法登錄了

4.1.4 查看命令SHOW

//1.查看有哪些數據庫
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| chengweihong       |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

//2.查看數據庫中有哪些表格(要看那個數據的表格就先進入到數據庫中)
mysql> use chengweihong
Database changed
mysql> show tables;
+------------------------+
| Tables_in_chengweihong |
+------------------------+
| cwh                    |
+------------------------+
1 row in set (0.00 sec)

//3.查看支持的全部字符集
mysql> show character set;
+----------+---------------------------------+---------------------+--------+
| 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.01 sec)

//4.查看當前數據庫支持的全部存儲引擎
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

//5.不進入某數據庫而列出其包含的全部表
mysql> show tables from chengweihong;
+------------------------+
| Tables_in_chengweihong |
+------------------------+
| cwh                    |
+------------------------+
1 row in set (0.00 sec)

//6.查看錶結構
//語法:DESC [db_name.]table_name;
mysql> desc chengweihong.cwh;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | varchar(100) | YES  |     | NULL    |       |
| age   | tinyint(4)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

//7.查看某表的建立命令
//語法:SHOW CREATE TABLE table_name;
mysql> show create table cwh;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                             |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| cwh   | CREATE TABLE `cwh` (
  `id` int(11) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `age` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//查看某表的狀態
//語法:SHOW TABLE STATUS LIKE 'table_name'\G
mysql> show create table cwh\G;
*************************** 1. row ***************************
       Table: cwh
Create Table: CREATE TABLE `cwh` (
  `id` int(11) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `age` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

4.1.5 獲取幫助

//獲取建立表的幫助
mysql> help create table
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    [(create_definition,...)]
    [table_options]
    [partition_options]
    [IGNORE | REPLACE]
    [AS] query_expression

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    { LIKE old_tbl_name | (LIKE old_tbl_name) }

4.2 DML操做(數據操控語言)

DML操做包括增(INSERT)、刪(DELETE)、改(UPDATE)、查(SELECT),均屬針對表的操做。

4.2.1 INSERT語句

1.一次插入一條完整數據

mysql> insert into cwh value(1,'tom',10);
Query OK, 1 row affected (0.01 sec)

mysql> select * from cwh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | tom  |   10 |
+----+------+------+
1 row in set (0.00 sec)

2.一次插入多條完整數據

mysql> insert into cwh values(2,'jerry',20),(3,'natasha',30)
    -> ; //由於最後沒有輸入分號
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from cwh
    -> ;  //由於ui後沒輸入;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
+----+---------+------+
3 rows in set (0.00 sec)

3.一次插入一條指定字段的數據

mysql> insert into cwh(id,name) value(4,'aaa');
Query OK, 1 row affected (0.00 sec)
mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     | NULL |
+----+---------+------+
4 rows in set (0.00 sec)

4.一次插入多條指定字段的數據

mysql> insert into cwh(id,name) values(5,'bbb'),(6,'ccc');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from cwh
    -> ;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     | NULL |
|  5 | bbb     | NULL |
|  6 | ccc     | NULL |
+----+---------+------+
6 rows in set (0.00 sec)

4.2.2 SELECT語句

字段column表示法

表示符 表示
* 全部字段
as 字段別名, 當名字很長時用別名代替

條件判斷語句WHERE

操做類型 經常使用操做符
操做符 >,<,>=,<=,=,!=
BETWEEN column# AND column#
LIKE:模糊匹配
RLIKE:基於正則表達式進行模式匹配
IS NOT NULL:非空
IS NULL:空
條件邏輯操做 AND,OR,NOT

ORDER BY:排序,默認爲升序(ASC)

ORDER BY語句 意義
ORDER BY 'column_name' 根據column_name進行升序排序
ORDER BY 'column_name'DESC 根據column_name進行降序排序
ORDER BY ’column_name' LIMIT 2 根據column_name進行升序排序
並只取前2個結果
ORDER BY ‘column_name' LIMIT 1,2 根據column_name進行升序排序而且略過第1個結果取後面的2個結果

//DML操做之查操做select
//語法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

1.查看錶的全部內容

mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     | NULL |
|  5 | bbb     | NULL |
|  6 | ccc     | NULL |
+----+---------+------+
6 rows in set (0.00 sec)

2.按字段查看錶的內容

mysql> select name from cwh;
+---------+
| name    |
+---------+
| tom     |
| jerry   |
| natasha |
| aaa     |
| bbb     |
| ccc     |
+---------+
6 rows in set (0.00 sec)

3.查看錶的內容並按某字段升序排序

mysql> select * from cwh order by age;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  4 | aaa     | NULL |
|  5 | bbb     | NULL |
|  6 | ccc     | NULL |
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
+----+---------+------+
6 rows in set (0.00 sec)

4.查看錶的內容按升序排序取前兩個

mysql> select * from cwh order by id limit 2;
+----+-------+------+
| id | name  | age  |
+----+-------+------+
|  1 | tom   |   10 |
|  2 | jerry |   20 |
+----+-------+------+
2 rows in set (0.00 sec)

5.查看錶的內容按升序排序跳過第一個取後兩個

mysql> select * from cwh order by id limit 1,2;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
+----+---------+------+
2 rows in set (0.00 sec)

6.查看錶的內容只打印age大於25的信息

mysql> select * from cwh where age >=25;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  3 | natasha |   30 |
+----+---------+------+
1 row in set (0.00 sec)

7.查看錶的內容只打印age=25和name=tom的信息

mysql> select * from cwh where age=10 and name='tom';
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | tom  |   10 |
+----+------+------+
1 row in set (0.00 sec)

8.查看錶格打印id在2-4之間的信息

mysql> select * from cwh where id between 2 and 4;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     | NULL |
+----+---------+------+
3 rows in set (0.00 sec)

9.查看錶格打印age爲空的信息

mysql> select * from cwh where age is null;
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | aaa  | NULL |
|  5 | bbb  | NULL |
|  6 | ccc  | NULL |
+----+------+------+
3 rows in set (0.00 sec)

10.查看錶格打印age不爲空的信息

mysql> select * from cwh where age is not null;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
+----+---------+------+
3 rows in set (0.00 sec)

4.2.3 update語句

//DML操做之改操做update

//語法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

注意:此語句只能一條一條的修改記錄,能夠修改一條記錄中的多個字段

1.修改表中的aaa的age由null改成40

mysql> update cwh set age=40 where name='aaa';
Query OK, 1 row affected (0.00 sec)
mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     |   40 |
|  5 | bbb     | NULL |
|  6 | ccc     | NULL |
+----+---------+------+
6 rows in set (0.00 sec)

2.修改表中一行記錄中多個字段將id=6的ccc改成cwh,age改成60

mysql> update cwh set name='cwh',age=60 where id=6;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     |   40 |
|  5 | bbb     | NULL |
|  6 | cwh     |   60 |
+----+---------+------+
6 rows in set (0.00 sec)

4.2.4 delete語句

//DML操做之刪操做delete

//語法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

1.刪除某條記錄

mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     |   40 |
|  5 | bbb     | NULL |
|  6 | cwh     |   60 |
+----+---------+------+
6 rows in set (0.00 sec)

mysql> delete from cwh where id=5;
Query OK, 1 row affected (0.00 sec)

mysql> select * from cwh;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | tom     |   10 |
|  2 | jerry   |   20 |
|  3 | natasha |   30 |
|  4 | aaa     |   40 |
|  6 | cwh     |   60 |
+----+---------+------+
5 rows in set (0.00 sec)

2.刪除整個表的內容

mysql> select * from cwh111;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | qqq  |   10 |
|  2 | www  |   20 |
+----+------+------+
2 rows in set (0.00 sec)

mysql> delete from cwh111;
Query OK, 2 rows affected (0.00 sec)

mysql> select * from cwh111;
Empty set (0.00 sec)

4.2.5 truncate語句

truncate與delete的區別:

語句類型 特色
delete DELETE刪除表內容時僅刪除內容,但會保留表結構
DELETE語句每次刪除一行,並在事務日誌中爲所刪除的每行記錄一項
能夠經過回滾事務日誌恢復數據
很是佔用空間
truncate 刪除表中全部數據,且沒法恢復
表結構、約束和索引等保持不變,新添加的行計數值重置爲初始值
執行速度比DELETE快,且使用的系統和事務日誌資源少
經過釋放存儲表數據所用的數據頁來刪除數據,而且只在事務日誌中記錄頁的釋放
對於有外鍵約束引用的表,不能使用TRUNCATE TABLE刪除數據
不能用於加入了索引視圖的表
mysql> select * from cwh111;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | qqq  |   10 |
|  2 | www  |   20 |
+----+------+------+
2 rows in set (0.00 sec)

mysql> truncate cwh111;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from cwh111;
Empty set (0.00 sec)

4.3 DCL操做

4.3.1 建立受權grant

權限類型(priv_type)

權限類型 表明什麼?
ALL 全部權限
SELECT 讀取內容的權限
INSERT 插入內容的權限
UPDATE 更新內容的權限
DELETE 刪除內容的權限

指定要操做的對象db_name.table_name

表示方式 意義
*.* 全部庫的全部表
db_name 指定庫的全部表
db_name.table_name 指定庫的指定表

WITH GRANT OPTION:被受權的用戶可將本身的權限副本轉贈給其餘用戶,說白點就是將本身的權限徹底複製給另外一個用戶。不建議使用。

語法:GRANT priv_type,... ON [object_type] db_name.table_name TO ‘username'@'host' [IDENTIFIED BY 'password'] [WITH GRANT OPTION];

1.受權cwh用戶在數據庫本機上登陸訪問全部數據庫

mysql> grant all on *.* to cwh@127.0.0.1 identified by '+7p6Mg2JsHgX1bIaOSwSykG8O2M='; //此處密碼使用openssl rand 20 -base64 生成
mysql> show grants for cwh@127.0.0.1
    -> ;
+--------------------------------------------------+
| Grants for cwh@127.0.0.1                         |
+--------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'cwh'@'127.0.0.1' |
+--------------------------------------------------+
1 row in set (0.00 sec)

2.受權cwh用戶在192.168.112.149上遠程登陸訪問chengweihong數據庫

//首先受權
mysql> grant all on chengweihong.* to cwh@192.168.112.149 identifiied by '+7p6Mg2JsHgX1bIaOSwSykG8O2M=';
Query OK, 0 rows affected, 1 warning (0.00 sec)
//在查看受權內容
mysql> show grants for cwh@192.168.112.149;
+---------------------------------------------------------------------+
| Grants for cwh@192.168.112.149                                      |
+---------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cwh'@'192.168.112.149'                       |
| GRANT ALL PRIVILEGES ON `chengweihong`.* TO 'cwh'@'192.168.112.149' |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)
//最後在192.168.112.149主機上驗證
[root@146 ~]# mysql -ucwh -p -h192.168.112.146
Enter password: 

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| chengweihong       |
+--------------------+
2 rows in set (0.00 sec)


MySQL [chengweihong]> show tables;
+------------------------+
| Tables_in_chengweihong |
+------------------------+
| cwh                    |
| cwh111                 |
+------------------------+
2 rows in set (0.00 sec)

3.受權cwh用戶在全部位置上遠程登陸訪問chengweihong數據庫的cwh表

//首先受權
mysql> grant all on chengweihong.cwh to 'cwh'@'%' identified by '+7p6Mg2JsHgX1bIaOSwSykG8O2M=';
Query OK, 0 rows affected, 1 warning (0.00 sec)
//在查看權限
mysql> show grants for cwh@'%';
+-----------------------------------------------------------+
| Grants for cwh@%                                          |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cwh'@'%'                           |
| GRANT ALL PRIVILEGES ON `chengweihong`.`cwh` TO 'cwh'@'%' |
+-----------------------------------------------------------+
2 rows in set (0.00 sec)
//在146主機上驗證
[root@146 ~]# mysql -ucwh -p -h192.168.112.146
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| chengweihong       |
+--------------------+
2 rows in set (0.00 sec)

MySQL [(none)]> show tables from chengweihong;
+------------------------+
| Tables_in_chengweihong |
+------------------------+
| cwh                    |
+------------------------+
1 row in set (0.00 sec)

4.3.2 查看受權

1.查看當前登陸用戶的受權信息

mysql> show grants;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION        |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)

2.查看指定用戶cwh的受權信息

mysql> show grants for cwh@'%';
+-----------------------------------------------------------+
| Grants for cwh@%                                          |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cwh'@'%'                           |
| GRANT ALL PRIVILEGES ON `chengweihong`.`cwh` TO 'cwh'@'%' |
+-----------------------------------------------------------+
2 rows in set (0.00 sec)

4.3.3 取消受權REVOKE

//語法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';

1.取消對cwh用戶的受權

mysql> revoke all on chengweihong.cwh from cwh@'%';
Query OK, 0 rows affected (0.00 sec)

mysql> show grants for cwh@'%';
+---------------------------------+
| Grants for cwh@%                |
+---------------------------------+
| GRANT USAGE ON *.* TO 'cwh'@'%' |
+---------------------------------+
1 row in set (0.00 sec)

注意:mysql服務進程啓動時會讀取mysql庫中的全部受權表至內存中:

  • GRANT或REVOKE等執行權限操做會保存於表中,mysql的服務進程會自動重讀受權表,並更新至內存中
  • 對於不可以或不能及時重讀受權表的命令,可手動讓mysql的服務進程重讀受權表

刷新受權表:

mysql> FLUSH PRIVILEGES;

相關文章
相關標籤/搜索