MySQL基礎學習手冊

前言:MariaDB的目的是完全兼容MySQL,包括API和命令行,使之能輕鬆成爲MySQL的代替品。由於CentOS7裏軟件庫已經把mysql刪除,使用MariaDB代替,所以我們在項目部署的時候也就直接使用了MariaDB。

用簡單的例子來學習Mysql的用法,初學者可以用來快速學習,學過的也可以拿來複習,用了csdn的目錄功能在PC端可以通過點擊目錄自動跳轉到相應位置正,在持續更新!
製作不易,覺得可以的話可以留個贊謝謝啦!
話不多說直接上乾貨!

一、Mysql的基本操作

1.安裝服務

[root@a ~]# yum install mariadb-server mariadb 
[root@a ~]# systemctl start mariadb
[root@a ~]# systemctl enable mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@a ~]# firewall-cmd --permanent --add-service
[root@a ~]# firewall-cmd --reload
success

2.登錄Mysql

(1)查看服務是否開啓

[root@a ~]# netstat -tulnp |grep mysql
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      
2208/mysqld

(2)安全安裝mysql

[root@a ~]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!
...此處省略安裝內容...

(3)登錄mysql

[root@a ~]# mysql -uroot -pa
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 16
Server version: 5.5.64-MariaDB MariaDB Server

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

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

MariaDB [(none)]>

3.MySQL建,查,選,刪庫

1.mysql命令規則:要在最後加上;(英文輸入法分號)表示命令結束
2.在linux中用mysql可以用tab鍵補全
3.mysql內命令不區分大小寫,比如CREATE=create
4.delete 和 truncate 僅僅刪除表數據,drop 連表數據和表結構一起刪除,打個比方,delete 是單殺,truncate 是團滅,drop 是把電腦摔了。

(1)創建數據庫create

[root@a ~]# mysqladmin -uroot -pa create test2
MariaDB [(none)]> create database test1;
Query OK, 1 row affected (0.00 sec)

(2)查詢數據庫show

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test1              |
| test2              |
+--------------------+
5 rows in set (0.00 sec)

(3)選擇數據庫use

MariaDB [(none)]> use test1;
Database changed
MariaDB [test1]> use test2;
Database changed
MariaDB [test2]> use  mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

(4)刪除數據庫
在操作中會有不少的錯誤,學會看報錯信息是個解決問題的好方法,如下根據提示(for the right syntax to use near ‘test2’ at line 1)發現test2附近語法錯誤,檢查後發現沒有寫databases,加上後便可以解決!

[root@a ~]# mysqladmin -uroot -pa drop test1
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'test1' database [y/N] y
Database "test1" dropped
MariaDB [mysql]> drop test2;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'test2' at line 1
MariaDB [mysql]> drop database test2;
Query OK, 0 rows affected (0.01 sec)

4.MySQL 數據類型

1.經常變化的字段用 varchar
2.知道固定長度的用 char
3.儘量用 varchar
4.超過 255 字符的只能用 varchar 或者 text
5.varchar 的地方不用 text
6.使用varchar必須帶範圍!

(1)數值類型放圖了,可在菜鳥教程找到
在這裏插入圖片描述
(2)日期和時間類型
在這裏插入圖片描述(3)字符串類型
在這裏插入圖片描述

5.建、查、刪表

1.建立、查詢、刪除表要在進入數據庫的前提下進行操作
2.數據類型後面不填的話默認是最高位
3.如果你不想字段爲 NULL 可以設置字段的屬性爲 NOT NULL, 在操作數據庫時如果輸入該字段的數據爲NULL ,就會報錯。

4.delete 和 truncate 僅僅刪除表數據,drop 連表數據和表結構一起刪除,打個比方,delete 是單殺,truncate 是團滅,drop 是把電腦摔了。
5.使用varchar必須帶範圍!
6.表名不能是mysql中數據類型等關鍵字。
(1)建表

MariaDB [test1]> create table book(name varchar(255),price int,date date);
Query OK, 0 rows affected (0.01 sec)

兩種方式都可以建表,看個人習慣!

MariaDB [test1]> create table book(
    -> name varchar(255),
    -> price int(11),
    -> date date)
    -> ;
ERROR 1050 (42S01): Table 'book' already exists

(2)查表
1.在數據庫查看錶

MariaDB [test1]> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| book            |
+-----------------+
1 row in set (0.00 sec)

2.查看錶結構

MariaDB [test1]> desc book;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| name  | char(1) | YES  |     | NULL    |       |
| price | int(11) | YES  |     | NULL    |       |
| date  | date    | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

(3)刪除表

MariaDB [test1]> drop table book;
Query OK, 0 rows affected (0.00 sec)

6.插入數據

1.添加數據的時候可以規定列進行添加。
如果所有的列都要添加數據可以不規定列進行添加數據:

MariaDB [test1]> insert into book(name,price,date) values ("a","8","2020-04-14");
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO runoob_tbl
    -> VALUES
    -> (0, "JAVA 教程", "RUNOOB.COM", '2016-05-06');

2.INSERT 插入多條數據

INSERT INTO table_name  (field1, field2,...fieldN)  VALUES  (valueA1,valueA2,...valueAN),(valueB1,valueB2,...valueBN),(valueC1,valueC2,...valueCN)......;
MariaDB [test1]> insert into book values("水滸","88","2020-04-13"),("紅樓夢","99","2020-04-13"),("西遊記","100","2020-04-13");
Query OK, 3 rows affected, 3 warnings (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 3

二、Mysql的數據查詢

(1).不顯示中文內容是因爲字符編碼搞的鬼,設置下就可以了

•vim /etc/my.cnf.d/client.cnf 文件,添加如下內容

[client]

default-character-set=utf8

•vim /etc/my.cnf.d/mysql-clients.cnf文件,添加如下內容

[mysql]
default-character-set=utf8

•vim /etc/my.cnf 文件,添加如下內容

[mysqld]
character-set-server=utf8
default-storage-engine=INNODB

•重啓服務

# systemctl restart mariadb

1.查詢表內數據

1.SQL中用select來查看數據,select後面跟是要查看錶格的列頭,查幾個跟幾個列頭,如果都要查可以用通配符,代表所有的意思。
2.as可以對查詢的內容進行重命名

MariaDB [test1]> select * from book;
+------+-------+------------+
| name | price | date       |
+------+-------+------------+
| ?    |    88 | 2020-04-13 |
| ?    |    99 | 2020-04-13 |
| ?    |   100 | 2020-04-13 |
+------+-------+------------+
6 rows in set (0.00 sec)

更改後

 MariaDB [test1]> select * from book;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸      |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

2.where子句

1.如需有條件地從表中選取數據,可將 WHERE 子句添加到 SELECT 語句中。
2.你可以使用 AND 或者 OR 指定一個或多個條件。
3.查詢語句中你可以使用一個或者多個表,表之間使用逗號, 分割,並使用WHERE語句來設定查詢條件。
在這裏插入圖片描述

MariaDB [test1]> select * from book where name="水滸";
+--------+-------+------------+
| name   | price | date       |
+--------+-------+------------+
| 水滸   |    88 | 2020-04-13 |
+--------+-------+------------+
1 row in set (0.00 sec)

MariaDB [test1]> select * from book where price=100 and date="2020-04-13";
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
1 row in set (0.00 sec)


MariaDB [test1]> select * from book where price=100 or date="2020-04-13";
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸      |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

3.UPDATE 更新數據

1.你可以同時更新一個或多個字段。
2.你可以在一個單獨表中同時更新數據。
3.你可以在 WHERE 子句中指定任何條件。

MariaDB [test1]> update book set name="水滸傳" where price=88;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0


MariaDB [test1]> select * from book;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

4.DELETE 刪除數據

1.如果沒有指定 WHERE 子句,MySQL 表中的所有記錄將被刪除。
2.你可以在 WHERE 子句中指定任何條件
3.您可以在單個表中一次性刪除記錄。
4.delete 和 truncate 僅僅刪除表數據,drop 連表數據和表結構一起刪除,打個比方,delete 是單殺,truncate 是團滅,drop 是把電腦摔了。

  MariaDB [a]> select * from book;
+------+-------+------------+
| name | price | date       |
+------+-------+------------+
| ?    |    66 | 2020-04-13 |
| ?    |    88 | 2020-04-13 |
| ?    |    99 | 2020-04-13 |
| ?    |   100 | 2020-04-13 |
| ?    |    88 | 2020-04-13 |
| a    |     8 | 2020-04-14 |
+------+-------+------------+
6 rows in set (0.00 sec)

MariaDB [a]> delete from book where price=8;
Query OK, 1 row affected (0.00 sec)

MariaDB [a]> select * from book;
+------+-------+------------+
| name | price | date       |
+------+-------+------------+
| ?    |    66 | 2020-04-13 |
| ?    |    88 | 2020-04-13 |
| ?    |    99 | 2020-04-13 |
| ?    |   100 | 2020-04-13 |
| ?    |    88 | 2020-04-13 |
+------+-------+------------+
5 rows in set (0.00 sec)

MariaDB [a]> delete from book;
Query OK, 5 rows affected (0.00 sec)

MariaDB [a]> select * from book;
Empty set (0.00 sec)

5.LIKE 子句

1.like 匹配/模糊匹配,會與 % 和 _ 結合使用。
2.在 where like 的條件查詢中,SQL 提供了四種匹配方式。
%:表示任意 0 個或多個字符。可匹配任意類型和長度的字符,有些情況下若是中文,請使用兩個百分號(%%)表示。
:表示任意單個字符。匹配單個任意字符,它常用來限制表達式的字符長度語句。
[]:表示括號內所列字符中的一個(類似正則表達式)。指定一個字符、字符串或範圍,要求所匹配對象爲它們中的任一個。
[^] :表示不在括號所列之內的單個字符。其取值和 [] 相同,但它要求所匹配對象爲指定字符以外的任一個字符。
查詢內容包含通配符時,由於通配符的緣故,導致我們查詢特殊字符 “%”、“
”、“[” 的語句無法正常實現,而把特殊字符用 “[ ]” 括起便可正常查詢。

MariaDB [test1]> select * from book where name like '水%';
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
+-----------+-------+------------+
1 row in set (0.00 sec)

MariaDB [test1]> select * from book where name like '%%';
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

MariaDB [test1]> select * from book where name like '_樓_';
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 紅樓夢    |    99 | 2020-04-13 |
+-----------+-------+------------+
1 row in set (0.00 sec)

6.排序

MariaDB [test1]> select * from book order by price desc;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 西遊記    |   100 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 水滸傳    |    88 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

MariaDB [test1]> select * from book order by price asc;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
+-----------+-------+------------+
3 rows in set (0.00 sec)

7.分組

1.GROUP BY 語句根據一個或多個列對結果集進行分組。
常和 COUNT, SUM, AVG,等函數一起使用。

2.GROUP by 的用法很多要多加練習!
3.as可以對查詢的內容進行重命名
4.WITH ROLLUP(rollup的意思就是歸納!) 可以實現在分組統計數據基礎上再進行相同的統計(SUM,AVG,COUNT…)。其中記錄 NULL 表示所有人的登錄次數。我們可以使用 coalesce 來設置一個可以取代 NUll 的名稱select coalesce(a,b,c);

MariaDB [test1]> select * from book;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
| 水滸傳    |    90 | 2020-01-01 |
+-----------+-------+------------+
4 rows in set (0.00 sec)


MariaDB [test1]> select name,count(*) from book group by name;
+-----------+----------+
| name      | count(*) |
+-----------+----------+
| 水滸傳    |        2 |
| 紅樓夢    |        1 |
| 西遊記    |        1 |
+-----------+----------+
3 rows in set (0.00 sec)

MariaDB [test1]> select name,sum(price) as total from book group  by name with rollup;
+-----------+-------+
| name      | total |
+-----------+-------+
| 水滸傳    |   178 |
| 紅樓夢    |    99 |
| 西遊記    |   100 |
| NULL      |   377 |
+-----------+-------+
4 rows in set (0.00 sec)

MariaDB [test1]> select coalesce(name,'total') as name,sum(price) as total from book group  by name with rollup;
+-----------+-------+
| name      | total |
+-----------+-------+
| 水滸傳    |   178 |
| 紅樓夢    |    99 |
| 西遊記    |   100 |
| total     |   377 |
+-----------+-------+
4 rows in set, 1 warning (0.00 sec)

8.多表查詢

1. 以上內容比較簡單容易理解,但是在真正的應用中經常需要從多個數據表中讀取數據。
2. INNER JOIN(內連接,或等值連接):獲取兩個表中字段匹配關係的記錄。
LEFT JOIN(左連接):獲取左表所有記錄,即使右表沒有對應匹配的記錄。
RIGHT JOIN(右連接): 與 LEFT JOIN 相反,用於獲取右表所有記錄,即使左表沒有對應匹配的記錄。

3.在這裏插入圖片描述
4.在這裏插入圖片描述
5.在這裏插入圖片描述

MariaDB [test1]> select * from book;
+-----------+-------+------------+
| name      | price | date       |
+-----------+-------+------------+
| 水滸傳    |    88 | 2020-04-13 |
| 紅樓夢    |    99 | 2020-04-13 |
| 西遊記    |   100 | 2020-04-13 |
| 水滸傳    |    90 | 2020-01-01 |
+-----------+-------+------------+
4 rows in set (0.00 sec)

MariaDB [test1]> select * from num;
+-----------+----------+
| name      | ordernum |
+-----------+----------+
| 水滸傳    |        1 |
| 紅樓夢    |        3 |
| 西遊記    |        2 |
+-----------+----------+
3 rows in set (0.00 sec)

#內連接
MariaDB [test1]> select book.name,book.price,book.date,num.ordernum from book inner join num where book.name=num.name;
+-----------+-------+------------+----------+
| name      | price | date       | ordernum |
+-----------+-------+------------+----------+
| 水滸傳    |    88 | 2020-04-13 |        1 |
| 紅樓夢    |    99 | 2020-04-13 |        3 |
| 西遊記    |   100 | 2020-04-13 |        2 |
| 水滸傳    |    90 | 2020-01-01 |        1 |
+-----------+-------+------------+----------+
4 rows in set (0.00 sec)

#左連接,左表沒有對應的項的情況,會顯示null
MariaDB [test1]> select book.name,num.ordernum from book left join num on book.name=num.name;
+--------------+----------+
| name         | ordernum |
+--------------+----------+
| 水滸傳       |        1 |
| 紅樓夢       |        3 |
| 西遊記       |        2 |
| 三國演藝     |     NULL |
+--------------+----------+
4 rows in set (0.00 sec)

#右連接,以右表爲主,右表多出的將不顯示
MariaDB [test1]> select book.name,num.ordernum from book right join num on book.name=num.name;
+-----------+----------+
| name      | ordernum |
+-----------+----------+
| 水滸傳    |        1 |
| 紅樓夢    |        3 |
| 西遊記    |        2 |
+-----------+----------+
3 rows in set (0.00 sec)

9.處理NULL值

1.我們已經知道 MySQL 使用 SQL SELECT 命令及 WHERE 子句來讀取數據表中的數據,但是當提供的查詢條件字段爲 NULL 時,該命令可能就無法正常工作。
2. IS NULL: 當列的值是 NULL,此運算符返回 true。
IS NOT NULL: 當列的值不爲 NULL, 運算符返回 true。
<=>: 比較操作符(不同於 = 運算符),當比較的的兩個值相等或者都爲 NULL 時返回 true。

MariaDB [test1]> create table nulll(name varchar(255) not null, price int);
Query OK, 0 rows affected (0.00 sec)

MariaDB [test1]> insert into nulll values("吳承恩","max"),("羅貫中","maxx"),("雪芹",null),("施耐庵",null);
Query OK, 4 rows affected, 2 warnings (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 2

MariaDB [test1]> select * from nulll;
+-----------+-------+
| name      | price |
+-----------+-------+
| 吳承恩    |     0 |
| 羅貫中    |     0 |
| 曹雪芹    |  NULL |
| 施耐庵    |  NULL |
+-----------+-------+
4 rows in set (0.00 sec)

#原先的方式無法查看null值
MariaDB [test1]> select * from nulll where price=null;
Empty set (0.00 sec)

#採用is null查看空值對應數據
MariaDB [test1]> select * from nulll where price is null;
+-----------+-------+
| name      | price |
+-----------+-------+
| 曹雪芹    |  NULL |
| 施耐庵    |  NULL |
+-----------+-------+
2 rows in set (0.00 sec)

#採用is not null查看非空值對應數據
MariaDB [test1]> select * from nulll where price is not null;
+-----------+-------+
| name      | price |
+-----------+-------+
| 吳承恩    |     0 |
| 羅貫中    |     0 |
+-----------+-------+
2 rows in set (0.00 sec)

10.正則表達式

1.MySQL可以通過 LIKE …% 來進行模糊匹配。
2.MySQL 同樣也支持其他正則表達式的匹配, MySQL中使用 REGEXP 操作符來進行正則表達式匹配。

在這裏插入圖片描述

#查看name字段以水開頭的所有數據
MariaDB [test1]> SELECT name FROM book WHERE name REGEXP '^水';
+-----------+
| name      |
+-----------+
| 水滸傳    |
+-----------+
1 row in set (0.00 sec)

#查看name字段所有以記結尾的數據
MariaDB [test1]> SELECT name FROM book WHERE name REGEXP '記$';
+-----------+
| name      |
+-----------+
| 西遊記    |
+-----------+
1 row in set (0.00 sec)

#查看name字段以水開頭或者結尾以記結尾的所有數據
MariaDB [test1]> SELECT name FROM book WHERE name REGEXP '^水|記$';
+-----------+
| name      |
+-----------+
| 水滸傳    |
| 西遊記    |
+-----------+
2 rows in set (0.00 sec)

三、Mysql高級操作

1.Mysql事務

1.MySQL 事務主要用於處理操作量大,複雜度高的數據。
2.一般來說,事務是必須滿足4個條件(ACID)::原子性(Atomicity,或稱不可分割性)、一致性(Consistency)、隔離性(Isolation,又稱獨立性)、持久性(Durability)。

原子性:一個事務(transaction)中的所有操作,要麼全部完成,要麼全部不完成,不會結束在中間某個環節。事務在執行過程中發生錯誤,會被回滾(Rollback)到事務開始前的狀態,就像這個事務從來沒有執行過一樣。

一致性:在事務開始之前和事務結束以後,數據庫的完整性沒有被破壞。這表示寫入的資料必須完全符合所有的預設規則,這包含資料的精確度、串聯性以及後續數據庫可以自發性地完成預定的工作。

隔離性:數據庫允許多個併發事務同時對其數據進行讀寫和修改的能力,隔離性可以防止多個事務併發執行時由於交叉執行而導致數據的不一致。事務隔離分爲不同級別,包括讀未提交(Read uncommitted)、讀提交(read committed)、可重複讀(repeatable read)和串行化(Serializable)。

持久性:事務處理結束後,對數據的修改就是永久的,即便系統故障也不會丟失。

3.MYSQL 事務處理主要有兩種方法:

1、用 BEGIN, ROLLBACK, COMMIT來實現

BEGIN 開始一個事務
ROLLBACK 事務回滾
COMMIT 事務確認

2、直接用 SET 來改變 MySQL 的自動提交模式:

SET AUTOCOMMIT=0 禁止自動提交
SET AUTOCOMMIT=1 開啓自動提交
mysql> use RUNOOB;
Database changed
mysql> CREATE TABLE runoob_transaction_test( id int(5)) engine=innodb;  # 創建數據表
Query OK, 0 rows affected (0.04 sec)
 
mysql> select * from runoob_transaction_test;
Empty set (0.01 sec)
 
mysql> begin;  # 開始事務
Query OK, 0 rows affected (0.00 sec)
 
mysql> insert into runoob_transaction_test value(5);
Query OK, 1 rows affected (0.01 sec)
 
mysql> insert into runoob_transaction_test value(6);
Query OK, 1 rows affected (0.00 sec)
 
mysql> commit; # 提交事務
Query OK, 0 rows affected (0.01 sec)
 
mysql>  select * from runoob_transaction_test;
+------+
| id   |
+------+
| 5    |
| 6    |
+------+
2 rows in set (0.01 sec)
 
mysql> begin;    # 開始事務
Query OK, 0 rows affected (0.00 sec)
 
mysql>  insert into runoob_transaction_test values(7);
Query OK, 1 rows affected (0.00 sec)
 
mysql> rollback;   # 回滾
Query OK, 0 rows affected (0.00 sec)
 
mysql>   select * from runoob_transaction_test;   # 因爲回滾所以數據沒有插入
+------+
| id   |
+------+
| 5    |
| 6    |
+------+
2 rows in set (0.01 sec)

2.alter用法

1.刪除,添加或修改表字段

MariaDB [test1]> alter table book add a int;
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

#查看字段信息
MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
| a     | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

#用add添加字段
MariaDB [test1]> alter table book add b int;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
| b     | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

#使用drop刪除字段
MariaDB [test1]> alter table book drop b;
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

2.修改字段類型及名稱

(1).如果需要修改字段類型及名稱, 你可以在ALTER命令中使用 MODIFY 或 CHANGE 子句 。
(2).使用 CHANGE 子句, 語法有很大的不同。 在 CHANGE 關鍵字之後,緊跟着的是你要修改的字段名,然後指定新字段名及類型


#查看字段信息
MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
| a     | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

#使用change命令修改字段和字段類型
MariaDB [test1]> alter table book change a b varchar(255);
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
| b     | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

#使用modify命令修改字段和字段類型
MariaDB [test1]> alter table book modify b int;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

MariaDB [test1]> show columns from book;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
| date  | date         | YES  |     | NULL    |       |
| b     | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

3.更改表名

MariaDB [test1]> alter table book rename to books;
Query OK, 0 rows affected (0.00 sec)

MariaDB [test1]> select * from books;
+--------------+-------+------------+------+
| name         | price | date       | b    |
+--------------+-------+------------+------+
| 水滸傳       |    88 | 2020-04-13 | NULL |
| 紅樓夢       |    99 | 2020-04-13 | NULL |
| 西遊記       |   100 | 2020-04-13 | NULL |
| 三國演藝     |    91 | 2020-04-14 | NULL |
+--------------+-------+------------+------+
4 rows in set (0.00 sec)

4.修改字段默認值

MariaDB [test1]> desc nulll;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | NO   |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

#修改默認值
MariaDB [test1]> alter table nulll alter price set default 1000;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0


MariaDB [test1]> desc nulll;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | NO   |     | NULL    |       |
| price | int(11)      | YES  |     | 1000    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

#刪除默認值
MariaDB [test1]> alter table nulll alter price drop default;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [test1]> desc nulll;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | NO   |     | NULL    |       |
| price | int(11)      | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

3.查看mysql引擎

(1)看你的mysql現在已提供知什麼存儲引擎:

MariaDB [test1]> show engines;
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                          | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Percona-XtraDB, Supports transactions, row-level locking, and foreign keys       | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                                            | NO           | NO   | NO         |
| MyISAM             | YES     | Non-transactional engine with good performance and small data footprint          | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears)                   | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                                               | NO           | NO   | NO         |
| CSV                | YES     | Stores tables as CSV files                                                       | NO           | NO   | NO         |
| ARCHIVE            | YES     | gzip-compresses tables for a low storage footprint                               | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                        | NO           | NO   | NO         |
| FEDERATED          | YES     | Allows to access tables on other MariaDB servers, supports transactions and more | YES          | NO   | YES        |
| Aria               | YES     | Crash-safe tables with MyISAM heritage                                           | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
10 rows in set (0.00 sec)

(2)看你的mysql當前默認的存儲引擎

MariaDB [test1]> show variables like '%storage_engine%';
+------------------------+--------+
| Variable_name          | Value  |
+------------------------+--------+
| default_storage_engine | InnoDB |
| storage_engine         | InnoDB |
+------------------------+--------+
2 rows in set (0.00 sec)

(3)看某個表用了什麼引擎

MariaDB [test1]> show variables like '%storage_engine%';
+------------------------+--------+
| Variable_name          | Value  |
+------------------------+--------+
| default_storage_engine | InnoDB |
| storage_engine         | InnoDB |
+------------------------+--------+
2 rows in set (0.00 sec)

MariaDB [test1]> show create table books;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                           |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| books | CREATE TABLE `books` (
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `date` date DEFAULT NULL,
  `b` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

4.數據庫導出導入

1.導出

[root@a ~]# mysqldump -uroot -p test1 > test1.sql
Enter password:
[root@a ~]# ll
total 8
-rw-------. 1 root root 1260 Jan 30 17:12 anaconda-ks.cfg
-rw-r--r--. 1 root root 4062 Apr 14 00:17 test1.sql

2.導入

MariaDB [(none)]> create database b;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> use b
Database changed
MariaDB [b]> source /root/test1.sql;
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
....此處省略...

MariaDB [b]> show tables;
+-------------+
| Tables_in_b |
+-------------+
| books       |
| nulll       |
| num         |
| xs          |
+-------------+
4 rows in set (0.00 sec)

3.備份所有數據庫

[root@a ~]# mysqldump -uroot -p --all-databases > a.sql
Enter password:
[root@a ~]# ll
total 520
-rw-------. 1 root root   1260 Jan 30 17:12 anaconda-ks.cfg
-rw-r--r--. 1 root root 520847 Apr 14 00:25 a.sql
-rw-r--r--. 1 root root   4062 Apr 14 00:17 test1.sql

5.mysql用戶管理

1.添加用戶

1、本地環境
[root@a shell]# cat /etc/redhat-release 
CentOS Linux release 7.7.1908 (Core)
2、以root用戶登錄Mysql
[root@a ~]# mysql -uroot -pa
3、切換到mysql數據庫
MariaDB [(none)]> use mysql
4、添加用戶
//只允許指定ip連接
create user '新用戶名'@'localhost' identified by '密碼';
//允許所有ip連接(用通配符%表示)
create user '新用戶名'@'%' identified by '密碼';

實例:

MariaDB [mysql]> create user 'Jack'@'localhost' identified by 'a';
Query OK, 0 rows affected (0.00 sec)

2.刪除用戶

刪除用戶

DROP USER username@localhost;

3.給用戶授權

爲新用戶授權

//基本格式如下
grant all privileges on 數據庫名.表名 to '新用戶名'@'指定ip' identified by '新用戶密碼' ;
//示例
//允許訪問所有數據庫下的所有表
grant all privileges on *.* to '新用戶名'@'指定ip' identified by '新用戶密碼' ;
//指定數據庫下的指定表
grant all privileges on test.test to '新用戶名'@'指定ip' identified by '新用戶密碼' ;
6、設置用戶操作權限

//設置用戶擁有所有權限也就是管理員
grant all privileges on *.* to '新用戶名'@'指定ip' identified by '新用戶密碼' WITH GRANT OPTION;
//擁有查詢權限
grant select on *.* to '新用戶名'@'指定ip' identified by '新用戶密碼' WITH GRANT OPTION;
//其它操作權限說明,select查詢 insert插入 delete刪除 update修改
//設置用戶擁有查詢插入的權限
grant select,insert on *.* to '新用戶名'@'指定ip' identified by '新用戶密碼' WITH GRANT OPTION;
//取消用戶查詢的查詢權限
REVOKE select ON what FROM '新用戶名';

實例:

mysql> grant all privileges on *.* to 'yangxin'@'%' identified by 'yangxin123456' with grant option;
   
   all privileges:表示將所有權限授予給用戶。也可指定具體的權限,如:SELECT、CREATE、DROP等。
    on:表示這些權限對哪些數據庫和表生效,格式:數據庫名.表名,這裏寫“*”表示所有數據庫,所有表。如果我要指定將權限應用到test庫的user表中,可以這麼寫:test.user
    to:將權限授予哪個用戶。格式:”用戶名”@”登錄IP或域名”。%表示沒有限制,在任何主機都可以登錄。比如:”yangxin”@”192.168.0.%”,表示yangxin這個用戶只能在192.168.0IP段登錄
    identified by:指定用戶的登錄密碼
    with grant option:表示允許用戶將自己的權限授權給其它用戶

    可以使用GRANT給用戶添加權限,權限會自動疊加,不會覆蓋之前授予的權限,比如你先給用戶添加一個SELECT權限,後來又給用戶添加了一個INSERT權限,那麼該用戶就同時擁有了SELECT和INSERT權限。

修改後刷新權限
FLUSH PRIVILEGES;

未完待續…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章