MySQL數據庫for CentOS7 yum安裝、5.7.30編譯安裝和基礎操做

1. MySQL數據庫簡介

MySQL 是一種關係數據庫管理系統,關係數據庫將數據保存在不一樣的表中,而不是將全部數據放在一個大倉庫內,這樣就增長了速度並提升了靈活性。MySQL所使用的SQL語言是用於訪問數據庫的最經常使用標準化語言。node

關係數據庫管理系統(Relational Database Management System, RDBMS),是將數據組織爲相關的行和列的系統,而管理關係數據庫的計算機軟件就是關係數據庫管理系統 。mysql

數據庫通常分爲如下兩種:c++

  • 關係型數據庫;sql

  • 非關係型數據庫。

經常使用的關係型數據庫軟件有: MySQL、Mariadb、Oracle、SQL Server、 PostgreSQL、DB2等。shell

經常使用的非關係型數據庫軟件有: Redis、memcached、MongoDB。 數據庫

MySQL現階段有免費版本和付費版本,公司裏面使用MySQL多數都是使用免費版本。 vim

Mariadb數據庫是MySQL數據庫原來的團隊,後續獨立出來進行開發的徹底開源版本。 安全

1.1 MySQL引擎

MySQL引擎有不少,企業裏面主流的myisam、innodb兩種。性能優化

1.1.1 MyISAM

主要強調的是性能,其執行速度比InnoDB類型更快,但不提供事務支持,不支持外鍵,若是執行大量的select(查詢)操做,MyISAM是更好的選擇,支持表鎖。MyISAM引擎查詢性能高。服務器

1.1.2 InnoDB

提供事務,支持事務、外鍵、行級鎖等高級數據庫功能,可執行大量的insert或update,InnoDB引擎寫性能高。

1.2 MySQL數據庫安裝

MySQL安裝方式有兩種,一種是yum/rpm安裝,另一種是tar源碼安裝。

1.2.1 MySQL yum安裝

yum安裝方法很簡單,執行命令以下便可:

1.2.1.1 CentOS 6 yum安裝

[root@node01 ~]#yum install –y mysql-server mysql-devel mysql

1.2.1.2 CentOS 7 yum安裝

[root@node01 ~]# yum install -y mariadb mariadb-devel mariadb-server

1.2.1.3 查詢yum安裝的內容

[root@node01 ~]# rpm -qa|grep mariadb
mariadb-libs-5.5.65-1.el7.x86_64
mariadb-devel-5.5.65-1.el7.x86_64
mariadb-server-5.5.65-1.el7.x86_64
mariadb-5.5.65-1.el7.x86_64
[root@node01 ~]#

1.2.1.4 yum安裝mariadb程序

mariadb主配置目錄: /var/lib/mysql

mariadb數據目錄:/var/lib/mysql

mariadb命令目錄:/usr/bin

mariadb默認配置文件:/etc/my.cnf

mariadb啓動文件:/usr/bin

mariadb日誌文件:/var/log/mariadb

說明:Mariadb和 mysql數據庫軟件命令和配置都是相似的。

1.2.2 MySQL源碼安裝5.7版本

1.2.2.1 源碼編譯安裝前準備

  1. 由於CentOS系統自帶了mariadb,咱們須要把它先卸載。
[root@node02 ~]# rpm -qa|grep mariadb
mariadb-server-5.5.60-1.el7_5.x86_64
mariadb-libs-5.5.60-1.el7_5.x86_64
mariadb-5.5.60-1.el7_5.x86_64
[root@node02 ~]# 
[root@node02 ~]# yum -y remove mariadb mariadb-server mariadb-libs
  1. 建立用戶
[root@node02 ~]# useradd -s /sbin/nologin -M mysql      #提示mysql已存在能夠忽略此步驟
  1. 建立目錄並修改權限
[root@node02 ~]# mkdir -p /data/mysql
[root@node02 ~]# chown -R mysql.mysql /data
  1. 安裝MySQL相關依賴包
[root@node02 ~]# yum install -y gcc gcc-devel gcc-c++ gcc-c++-devel libaio* autoconf* automake* zlib* libxml* ncurses-devel ncurses libgcrypt* libtool* cmake openssl openssl-devel bison bison-devel perl-Data_Dumper boost boost-doc boost-devel
  1. 下載源碼並解壓
[root@node02 ~]# cd /usr/src/
[root@node02 src]# wget http://mirrors.163.com/mysql/Downloads/MySQL-5.7/mysql-5.7.30.tar.gz
[root@node02 src]# ls
debug  kernels  mysql-5.7.30.tar.gz
[root@node02 src]# tar xf mysql-5.7.30.tar.gz
[root@node02 src]# cd mysql-5.7.30/
[root@node02 mysql-5.7.30]#
  1. 下載boost(5.7版本更新以後有不少變化,好比如今安裝必需要安裝這個boost庫了)
[root@node02 mysql-5.7.30]# mkdir ./boost
[root@node02 mysql-5.7.30]# cd ./boost
[root@node02 boost]# wget http://nchc.dl.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.gz

說明:解壓等操做編譯的時候程序會作,這裏只需把包下載或者拷貝到這裏便可

1.2.2.2 源碼編譯安裝

  1. 編譯
[root@node02 boost]# cd ../
[root@node02 mysql-5.7.30]# cmake \
-DBUILD_CONFIG=mysql_release \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DMYSQL_DATADIR=/data/mysql \
-DSYSCONFDIR=/etc \
-DMYSQL_UNIX_ADDR=/tmp/mysql.sock \
-DSYSTEMD_PID_DIR=/data/mysql \
-DMYSQL_USER=mysql \
-DWITH_SYSTEMD=1 \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_MEMORY_STORAGE_ENGINE=1 \
-DWITH_READLINE=1 \
-DMYSQL_TCP_PORT=3306 \
-DENABLED_LOCAL_INFILE=1 \
-DENABLE_DOWNLOADS=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_DEBUG=0 \
-DMYSQL_MAINTAINER_MODE=0 \
-DWITH_SSL:STRING=system \
-DWITH_ZLIB:STRING=bundled \
-DDOWNLOAD_BOOST=1 \
-DWITH_BOOST=./boost
  1. 編譯參數介紹
cmake \
-DBUILD_CONFIG=mysql_release \                  #此選項使用Oracle使用的相同構建選項配置源分發,以生成官方MySQL版本的二進制分發。
-DCMAKE_BUILD_TYPE=RelWithDebInfo \             #要生成的構建類型 = 啓用優化並生成調試信息。這是默認的MySQL構建類型。
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \       #選項表示基本安裝目錄。
-DMYSQL_DATADIR=/data/mysql \                   #MySQL數據目錄的位置。
-DSYSCONFDIR=/etc \                             #默認my.cnf選項文件目錄。
-DMYSQL_UNIX_ADDR=/tmp/mysql.sock \             #服務器偵聽套接字鏈接的Unix套接字文件路徑。這必須是絕對路徑名。默認是/tmp/mysql.sock。
-DSYSTEMD_PID_DIR=/usr/local/mysql \            #當MySQL由systemd管理時,在其中建立PID文件的目錄的名稱。默認是 /var/run/mysqld; 這可能會根據INSTALL_LAYOUT值隱式更改 。
-DMYSQL_USER=mysql \                            #指定MySQL的啓動用戶
-DWITH_SYSTEMD=1 \                              #安裝systemd支持文件
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_MEMORY_STORAGE_ENGINE=1 \
-DWITH_READLINE=1 \
-DMYSQL_TCP_PORT=3306 \                          #配置 MySQL 監聽的端口號
-DENABLED_LOCAL_INFILE=1 \                       #使mysql客戶端具備load data infile的功能,該功能具備安全隱患  load data infile語句從一個文本文件中以很高的速度讀入一個表                
-DENABLE_DOWNLOADS=1 \                           #googlemock發行版的路徑,用於基於Google Test的單元測試。=1,CMake將從GitHub下載發行版。
-DWITH_PARTITION_STORAGE_ENGINE=1 \ 
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8 \                         #服務器字符集
-DDEFAULT_COLLATION=utf8_general_ci \            #服務器排序規則
-DWITH_DEBUG=0 \                                 #不包含調試支持。
-DMYSQL_MAINTAINER_MODE=0 \                      #是否啓用MySQL維護者特定的開發環境。若是啓用,此選項會致使編譯器警告變爲錯誤。
-DWITH_SSL:STRING=system \
-DWITH_ZLIB:STRING=bundled \
-DDOWNLOAD_BOOST=1 \                             #是否下載Boost庫。默認是OFF。
-DWITH_BOOST=./boost                             #指定Boost庫目錄位置。
  1. 查看編譯是否有異常
[root@node02 mysql-5.7.30]# echo $?              #返回結果爲0說明編譯無異常
  1. 源碼安裝
[root@node02 mysql-5.7.30]# make && make install

這個過程比較漫長,耐心等待一下

  1. 查看安裝是否有異常
[root@node02 mysql-5.7.30]# echo $?              #返回結果爲0說明編譯無異常

1.2.2.4 源碼安裝後配置

  1. 添加 systemd 服務控制
[root@node02 mysql-5.7.30]# cp ./scripts/mysqld.service /usr/lib/systemd/system
  1. 添加環境變量
[root@node02 mysql-5.7.30]# cat > /etc/profile.d/mysql.sh << EOF 
PATH=/usr/local/mysql/bin:$PATH
export PATH
EOF
[root@node02 mysql-5.7.30]# source /etc/profile
  1. 空密碼初始化數據庫
[root@node02 mysql-5.7.30]# /usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql
  1. 配置啓動MySQL
[root@node02 mysql-5.7.30]# systemctl enable mysqld.service
[root@node02 mysql-5.7.30]# systemctl daemon-reload
[root@node02 mysql-5.7.30]# systemctl start mysqld.service
[root@node02 mysql-5.7.30]# systemctl status mysqld.service

1.3 登陸數據庫服務器

1.3.1 經過unix套接字鏈接

1.3.1.1 直接經過mysql登陸,查看鏈接狀態

[root@node02 ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, 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> status
--------------
mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper

Connection id:          5
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.7.30 MySQL Community Server (GPL)
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /tmp/mysql.sock
Uptime:                 33 min 25 sec

Threads: 1  Questions: 17  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 0.008
--------------

mysql>

1.3.1.2 mysql -uroot -p登陸,查看鏈接狀態

[root@node02 ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.30 MySQL Community Server (GPL)

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

mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper

Connection id:          3
Current database:                                 #當前使用的那個數據庫,沒有選擇爲空
Current user:           root@localhost
SSL:                    Not in use                #是否使用加密
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;                         #結束符爲分號
Server version:         5.7.30 MySQL Community Server (GPL)
Protocol version:       10
Connection:             Localhost via UNIX socket #鏈接方式,本地套接字
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /tmp/mysql.sock
Uptime:                 17 min 33 sec

Threads: 1  Questions: 7  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 0.006
--------------

mysql>

1.3.2 經過tcp套接字鏈接

1.3.2.1 經過mysql -h127.0.0.1登陸服務器,查看狀態

[root@node02 ~]# mysql -h127.0.0.1
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.30 MySQL Community Server (GPL)

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

mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper

Connection id:          4
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.7.30 MySQL Community Server (GPL)
Protocol version:       10
Connection:             127.0.0.1 via TCP/IP
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
TCP port:               3306
Uptime:                 31 min 40 sec

Threads: 1  Questions: 12  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 0.006
--------------

mysql>

能夠看到鏈接id不一樣,套接字也不一樣,使用的是tcp/ip的套接字通訊。若是有時候遇到沒法經過本地套接字鏈接,可使用指定服務器ip鏈接。

1.4 經常使用命令操做

1.4.1 數據庫的操做命令

#查詢數據庫:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

mysql>

初始化後,默認會有四個數據庫:

  • information_schema:信息數據庫。主要保存着關於MySQL服務器所維護的 全部其餘數據庫的信息,如數據庫名,數據庫的表,表欄的數據類型與訪問權 限等。經過show databases;查看到數據庫信息,也是出自該數據庫中得SCHEMATA表。

  • mysql: mysql的核心數據庫。主要負責存儲數據庫的用戶、權限設置、關鍵字等mysql本身須要使用的控制和管理信息。

  • performance_schema :用於性能優化的數據庫。

    #查看數據庫的建立語句:

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

mysql>

​ mysql爲數據庫名。

#查看字符集命令:

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.00 sec)

  mysql>

#建立數據庫zabbix,字符集位gbk;

mysql> create database zabbix default character set gbk;
Query OK, 1 row affected (0.00 sec)

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

mysql>

#修改數據庫的字符集:

mysql> alter database zabbix default character set utf8;
Query OK, 1 row affected (0.00 sec)

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

mysql>

#建立數據庫:

mysql> create database zabbix charset=utf8; 
ERROR 1007 (HY000): Can't create database 'zabbix'; database exists
mysql> 

mysql> create database if not exists zabbix charset=gbk;
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql>

用上面的第二條命令建立數據庫,若是數據庫已經存在就不會報錯了。

#查看警告:

mysql> show warnings;
+-------+------+-------------------------------------------------+
| Level | Code | Message                                         |
+-------+------+-------------------------------------------------+
| Error | 1007 | Can't create database 'zabbix'; database exists |
+-------+------+-------------------------------------------------+
1 row in set (0.00 sec)

mysql>

#刪除數據庫:

mysql> drop database zabbix;
mysql>

或者:

mysql> drop database zabbix;
ERROR 1008 (HY000): Can't drop database 'zabbix'; database doesn't exist
mysql> 
mysql> drop database if exists zabbix;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

用上面第二種方式刪除數據庫,若是數據庫不存在就不會報錯了。

1.4.2 建立表命令

mysql> create table t1(id int(10) auto_increment primary key,name varchar(20),job varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql>

1.4.3 查看錶結構相關命令

查看全部表:

mysql> use mysql;
Database changed
mysql> 
mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| t1                        |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
32 rows in set (0.00 sec)

mysql>

或者

mysql> show tables from mysql;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| t1                        |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
32 rows in set (0.00 sec)

mysql>

查看全部表的詳細信息:

use mysql;

show table status\G

或者

show table status from mysql\G

查看某張表的詳細信息:

mysql> use mysql;
Database changed
mysql> 
mysql> show table status like "user"\G
*************************** 1. row ***************************
           Name: user
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 3
 Avg_row_length: 113
    Data_length: 340
Max_data_length: 281474976710655
   Index_length: 4096
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2020-06-01 14:58:34
    Update_time: 2020-06-01 14:58:35
     Check_time: NULL
      Collation: utf8_bin
       Checksum: NULL
 Create_options: 
        Comment: Users and global privileges
1 row in set (0.00 sec)

mysql>

或者

mysql> show table status from mysql like "user"\G
*************************** 1. row ***************************
           Name: user
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 3
 Avg_row_length: 113
    Data_length: 340
Max_data_length: 281474976710655
   Index_length: 4096
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2020-06-01 14:58:34
    Update_time: 2020-06-01 14:58:35
     Check_time: NULL
      Collation: utf8_bin
       Checksum: NULL
 Create_options: 
        Comment: Users and global privileges
1 row in set (0.00 sec)

mysql>

查看錶結構:

mysql> desc mysql.user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(32)                          | NO   | PRI |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | NO   |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed  | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime      | smallint(5) unsigned              | YES  |     | NULL                  |       |
| account_locked         | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)

mysql>

查看建立表的sql語句:

mysql> show create table mysql.user\G
*************************** 1. row ***************************
       Table: user
Create Table: CREATE TABLE `user` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
  `User` char(32) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Select_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Insert_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Update_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Delete_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Drop_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Reload_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Shutdown_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Process_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `File_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Grant_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `References_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Index_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_db_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Super_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tmp_table_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Lock_tables_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Execute_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_slave_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_client_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_user_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Event_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Trigger_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tablespace_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `ssl_type` enum('','ANY','X509','SPECIFIED') CHARACTER SET utf8 NOT NULL DEFAULT '',
  `ssl_cipher` blob NOT NULL,
  `x509_issuer` blob NOT NULL,
  `x509_subject` blob NOT NULL,
  `max_questions` int(11) unsigned NOT NULL DEFAULT '0',
  `max_updates` int(11) unsigned NOT NULL DEFAULT '0',
  `max_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `max_user_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `plugin` char(64) COLLATE utf8_bin NOT NULL DEFAULT 'mysql_native_password',
  `authentication_string` text COLLATE utf8_bin,
  `password_expired` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `password_last_changed` timestamp NULL DEFAULT NULL,
  `password_lifetime` smallint(5) unsigned DEFAULT NULL,
  `account_locked` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges'
1 row in set (0.00 sec)

mysql>

1.4.4 修改表結構相關命令

添加表字段:

mysql> alter table t1 add job1 varchar(20);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>

默認是加在後面,若是想加在第一列,或者某個字段後能夠進行指定:

#加在第一列

mysql> alter table t1 add job2 varchar(20) first;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>
mysql> desc t1;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| job2  | varchar(20) | YES  |     | NULL    |                |
| id    | int(10)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
| job   | varchar(10) | YES  |     | NULL    |                |
| job1  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

mysql>

#加在name字段後:

mysql> alter table t1 add job3 varchar(20) after name;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> desc t1;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| job2  | varchar(20) | YES  |     | NULL    |                |
| id    | int(10)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
| job3  | varchar(20) | YES  |     | NULL    |                |
| job   | varchar(10) | YES  |     | NULL    |                |
| job1  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql>

修改表字段名,須要將字段屬性寫全:

mysql> alter table t1 change id age int(5);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> desc t1;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| job2  | varchar(20) | YES  |     | NULL    |       |
| age   | int(5)      | NO   | PRI | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| job3  | varchar(20) | YES  |     | NULL    |       |
| job   | varchar(10) | YES  |     | NULL    |       |
| job1  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql>

id: 原字段

age: 新字段

修改表字段的屬性或者位置:

#修改字段的順序,把job3放在第一列:

mysql> alter table t1 modify job3 varchar(20) first;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> desc t1;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| job3  | varchar(20) | YES  |     | NULL    |       |
| job2  | varchar(20) | YES  |     | NULL    |       |
| age   | int(5)      | NO   | PRI | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| job   | varchar(10) | YES  |     | NULL    |       |
| job1  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql>

刪除表字段:

mysql> alter table t1 drop job3;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> desc t1;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| job2  | varchar(20) | YES  |     | NULL    |       |
| age   | int(5)      | NO   | PRI | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| job   | varchar(10) | YES  |     | NULL    |       |
| job1  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql>

1.4.5 增、刪、改、查

1.4.5.1 增

#全字段增長數據:

mysql> insert into t1 values(1,"xiaoming","it");
Query OK, 1 row affected (0.00 sec)

mysql>

或者

mysql> insert t1 values(2,"xiaohua","student");
Query OK, 1 row affected (0.00 sec)

mysql>

或者

mysql> insert t1 set name="xiaoming",job="teacher";
Query OK, 1 row affected (0.00 sec)

mysql>

#指定字段增長數據:

mysql> insert into t1(name) value("xiaoqiang"),("xiaowang");
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql>

1.4.5.2 刪

#物理刪除,數據就真沒有了

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

mysql> 
mysql> select * from t1;
+----+----------+---------+
| id | name     | job     |
+----+----------+---------+
|  2 | xiaohua  | student |
|  3 | xiaoming | teacher |
|  5 | xiaowang | NULL    |
+----+----------+---------+
3 rows in set (0.00 sec)

mysql>

#邏輯刪除,須要添加一個字段,默認設置爲0:

mysql> alter table t1 add isdelete bit default 0;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 
mysql> select * from t1;
+----+----------+---------+----------+
| id | name     | job     | isdelete |
+----+----------+---------+----------+
|  2 | xiaohua  | student |          |
|  3 | xiaoming | teacher |          |
|  5 | xiaowang | NULL    |          |
+----+----------+---------+----------+
3 rows in set (0.00 sec)

mysql>

#將isdelete字段設置爲1:

mysql> update t1 set isdelete=1 where id=3;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> 
mysql> select * from t1;
+----+----------+---------+----------+
| id | name     | job     | isdelete |
+----+----------+---------+----------+
|  2 | xiaohua  | student |          |
|  3 | xiaoming | teacher |         |
|  5 | xiaowang | NULL    |          |
+----+----------+---------+----------+
3 rows in set (0.00 sec)

mysql>

#而後查找isdelete字段爲0得數據便可過濾了:

mysql> select * from t1 where isdelete=0;
+----+----------+---------+----------+
| id | name     | job     | isdelete |
+----+----------+---------+----------+
|  2 | xiaohua  | student |          |
|  5 | xiaowang | NULL    |          |
+----+----------+---------+----------+
2 rows in set (0.00 sec)

mysql>

1.4.5.3 改

#修改表中得數據,不增長行,insert into會增長行: update t1 set name="xiaoxiao" where id=6; t1是表名,

name是字段名,

where後面是條件語句,若是沒有,就是對整個表得修改了,要慎重!

#修改多個字段用逗號分隔:

mysql> update t1 set name="xiaoqiang",job="engineer" where id=3 ;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> 
mysql> 
mysql> select * from t1;
+----+-----------+----------+----------+
| id | name      | job      | isdelete |
+----+-----------+----------+----------+
|  2 | xiaohua   | student  |          |
|  3 | xiaoqiang | engineer |         |
|  5 | xiaowang  | NULL     |          |
+----+-----------+----------+----------+
3 rows in set (0.00 sec)

mysql>

1.4.5.4 查

全字段查找,不建議:

mysql> select * from t1;
+----+-----------+----------+----------+
| id | name      | job      | isdelete |
+----+-----------+----------+----------+
|  2 | xiaohua   | student  |          |
|  3 | xiaoqiang | engineer |         |
|  5 | xiaowang  | NULL     |          |
+----+-----------+----------+----------+
3 rows in set (0.00 sec)

mysql>

查找指定字段:

mysql> select name,job from t1;
+-----------+----------+
| name      | job      |
+-----------+----------+
| xiaohua   | student  |
| xiaoqiang | engineer |
| xiaowang  | NULL     |
+-----------+----------+
3 rows in set (0.00 sec)

mysql>

1.4.9 根據運算符查找

>= 大於等於

= 等於

> 大於

< 小於

<= 小於等於

!= 不等於

查找id大於等於4的用戶id,用戶名及工做:

mysql> select id,name,job from t1 where id >=4;
+----+----------+------+
| id | name     | job  |
+----+----------+------+
|  5 | xiaowang | NULL |
+----+----------+------+
1 row in set (0.00 sec)

mysql>

and 多個條件同時知足

or 幾個條件,知足其一便可

查找id大於等於3,而且沒有標記刪除的數據

mysql> select id,name,job,isdelete from t1 where id>=3 and isdelete=0;
+----+----------+------+----------+
| id | name     | job  | isdelete |
+----+----------+------+----------+
|  5 | xiaowang | NULL |          |
+----+----------+------+----------+
1 row in set (0.00 sec)

mysql>

1.4.10 模糊查找

like 模糊查找

% 匹配任意多個字符

_ 匹配單個字符

查找名字中含有xiao字符的數據:

mysql> select id,name,job from t1 where name like "xiao%";
+----+-----------+----------+
| id | name      | job      |
+----+-----------+----------+
|  2 | xiaohua   | student  |
|  3 | xiaoqiang | engineer |
|  5 | xiaowang  | NULL     |
+----+-----------+----------+
3 rows in set (0.00 sec)

mysql>

插入一條數據,查找名字中含有xiao而且後面跟一個單字符的數據

mysql> insert t1(name) value("xiaom");
Query OK, 1 row affected (0.01 sec)

mysql> 

mysql> select id,name,job from t1 where name like "xiao_";
+----+-------+------+
| id | name  | job  |
+----+-------+------+
|  6 | xiaom | NULL |
+----+-------+------+
1 row in set (0.00 sec)

mysql>

1.4.11 範圍查找

in 表示非連續的範圍

between A and B 表示一個連續的範圍內

not 不在某個條件內

查找id等於2,3或者6的數據

mysql> select id,name,job from t1 where id in(2,3,6);
+----+-----------+----------+
| id | name      | job      |
+----+-----------+----------+
|  2 | xiaohua   | student  |
|  3 | xiaoqiang | engineer |
|  6 | xiaom     | NULL     |
+----+-----------+----------+
3 rows in set (0.00 sec)

mysql>

查找id在3到6之間數據(包含3和6):

mysql> select id,name,job from t1 where id between 3 and 6;
+----+-----------+----------+
| id | name      | job      |
+----+-----------+----------+
|  3 | xiaoqiang | engineer |
|  5 | xiaowang  | NULL     |
|  6 | xiaom     | NULL     |
+----+-----------+----------+
3 rows in set (0.00 sec)

mysql>

查找id不等於3,6的數據:

mysql> select id,name,job from t1 where id not in (3,6);
+----+----------+---------+
| id | name     | job     |
+----+----------+---------+
|  2 | xiaohua  | student |
|  5 | xiaowang | NULL    |
+----+----------+---------+
2 rows in set (0.00 sec)

mysql>

1.4.12 空值查找

is null查找空值

mysql> select id,name,job from t1 where job is null;
+----+----------+------+
| id | name     | job  |
+----+----------+------+
|  5 | xiaowang | NULL |
|  6 | xiaom    | NULL |
+----+----------+------+
2 rows in set (0.00 sec)

mysql>

1.4.13 聚合

mysql> select max(age) from t1;
+----------+
| max(age) |
+----------+
|       15 |
+----------+
1 row in set (0.01 sec)

mysql> 
mysql> select min(age) from t1;
+----------+
| min(age) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)

mysql> 
mysql> select count(*) from t1 where isdelete=0;
+----------+
| count(*) |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)

mysql>

1.4.14 排序

order by 字段 asc 根據「列」從小到大排序

根據id,從小到大進行排序:

mysql> select * from t1 order by id asc;
+----+-----------+------+----------+----------+
| id | name      | age  | job      | isdelete |
+----+-----------+------+----------+----------+
|  2 | xiaohua   |   10 | student  |          |
|  3 | xiaoqiang |    6 | engineer |         |
|  5 | xiaowang  |   15 | NULL     |          |
|  6 | xiaom     |   11 | NULL     |          |
+----+-----------+------+----------+----------+
4 rows in set (0.00 sec)

mysql>

order by字段 desc 根據「列」從大到小排序

根據id,從大到小進行排序:

mysql> select * from t1 order by id desc;
+----+-----------+------+----------+----------+
| id | name      | age  | job      | isdelete |
+----+-----------+------+----------+----------+
|  6 | xiaom     |   11 | NULL     |          |
|  5 | xiaowang  |   15 | NULL     |          |
|  3 | xiaoqiang |    6 | engineer |         |
|  2 | xiaohua   |   10 | student  |          |
+----+-----------+------+----------+----------+
4 rows in set (0.00 sec)

mysql>

1.4.15 分組

group by 字段

#根據名字分組,統計同名的個數:

mysql> select count(*),name from t1 group by name;
+----------+-----------+
| count(*) | name      |
+----------+-----------+
|        1 | xiaohua   |
|        1 | xiaom     |
|        1 | xiaoqiang |
|        2 | xiaowang  |
+----------+-----------+
4 rows in set (0.00 sec)

mysql>

1.4.16 限制

limit n; 顯示前n行

#顯示前三行

mysql> select * from t1 limit 3;
+----+-----------+------+----------+----------+
| id | name      | age  | job      | isdelete |
+----+-----------+------+----------+----------+
|  2 | xiaohua   |   10 | student  |          |
|  3 | xiaoqiang |    6 | engineer |         |
|  5 | xiaowang  |   15 | NULL     |          |
+----+-----------+------+----------+----------+
3 rows in set (0.00 sec)

mysql>

#顯示從第3行開始後的3行;

mysql> select * from t1 limit 3,3;
+----+----------+------+-------+----------+
| id | name     | age  | job   | isdelete |
+----+----------+------+-------+----------+
|  6 | xiaom    |   11 | NULL  |          |
|  9 | xiaowang |   18 | sales |         |
+----+----------+------+-------+----------+
2 rows in set (0.00 sec)

mysql>

#顯示從第3行開始後的4行

mysql> select * from t1 limit 4 offset 3;
+----+----------+------+-------+----------+
| id | name     | age  | job   | isdelete |
+----+----------+------+-------+----------+
|  6 | xiaom    |   11 | NULL  |          |
|  9 | xiaowang |   18 | sales |         |
+----+----------+------+-------+----------+
2 rows in set (0.00 sec)

mysql>

1.5 視圖的相關操做

視圖並非真實存在的表,主要是將經常使用的到字段或者數據整合成一個「表」。

1.5.1 建立視圖

#先建立表:

mysql> create table t2(id int(10) not null auto_increment primary key,name varchar(20),job varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql>

#插入數據:

mysql> insert t2 set name="xiaoming",job="it";
Query OK, 1 row affected (0.00 sec)

mysql> 
mysql> insert t2 set name="xiaowang",job="student";
Query OK, 1 row affected (0.00 sec)

mysql> 
mysql> insert t2 set name="xiaohong",job="teacher";
Query OK, 1 row affected (0.00 sec)

mysql>

#建立視圖:

mysql> create view v1 as select name,job from t1;
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> create view v2 as select * from t2 where id >= 2;
Query OK, 0 rows affected (0.00 sec)

mysql>

1.5.2 查看視圖

#查看全部視圖:

mysql> select * from information_schema.views where table_schema="mysql"\G
*************************** 1. row ***************************
       TABLE_CATALOG: def
        TABLE_SCHEMA: mysql
          TABLE_NAME: v1
     VIEW_DEFINITION: select `mysql`.`t1`.`name` AS `name`,`mysql`.`t1`.`job` AS `job` from `mysql`.`t1`
        CHECK_OPTION: NONE
        IS_UPDATABLE: YES
             DEFINER: root@localhost
       SECURITY_TYPE: DEFINER
CHARACTER_SET_CLIENT: utf8
COLLATION_CONNECTION: utf8_general_ci
*************************** 2. row ***************************
       TABLE_CATALOG: def
        TABLE_SCHEMA: mysql
          TABLE_NAME: v2
     VIEW_DEFINITION: select `mysql`.`t2`.`id` AS `id`,`mysql`.`t2`.`name` AS `name`,`mysql`.`t2`.`job` AS `job` from `mysql`.`t2` where (`mysql`.`t2`.`id` >= 2)
        CHECK_OPTION: NONE
        IS_UPDATABLE: YES
             DEFINER: root@localhost
       SECURITY_TYPE: DEFINER
CHARACTER_SET_CLIENT: utf8
COLLATION_CONNECTION: utf8_general_ci
2 rows in set (0.00 sec)

mysql>

#查看某個視圖結構:

mysql> desc v2;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(10)     | NO   |     | 0       |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| job   | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql>

#查看視圖內容:

mysql> select * from v2;
+----+----------+---------+
| id | name     | job     |
+----+----------+---------+
|  2 | xiaowang | student |
|  3 | xiaohong | teacher |
+----+----------+---------+
2 rows in set (0.00 sec)

mysql>

1.5.3 刪除視圖

mysql> drop view v2;
Query OK, 0 rows affected (0.00 sec)

mysql>

或者

mysql> drop view if exists v2;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

1.5.4 修改視圖

alter view v1 as select id,job from t1;

mysql> alter view v1 as select id,job from t1;
Query OK, 0 rows affected (0.00 sec)

mysql>

1.6 修改密碼

1.6.1 密碼爲空或者已知當前密碼

方法一:用SET PASSWORD命令

首先登陸MySQL。

格式:mysql> set password for用戶名@localhost = password('新密碼');

範例:

mysql> set password for root@localhost=password('123');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

方法二:在shell終端執行:

[root@node02 ~]# mysql -uroot -p -e "set password for root@localhost=password('123456');"
Enter password:        ------此處輸入原密碼
[root@node02 ~]#

ps:注意雙引號和單引號!!!

方法三:在shell終端用mysqladmin

格式:mysqladmin -u用戶名 -p舊密碼 password新密碼

範例:

[root@node02 ~]# mysqladmin -uroot -p123 password 123456
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@node02 ~]#

方法四:用UPDATE直接編輯user表 首先登陸MySQL。

mysql> use mysql; 

mysql 5.7之前版本
mysql> update user set password=password('123') where user='root' and host='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> 

mysql 5.7之後版本
mysql> update user set authentication_string=password('123') where user='root' and host='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql>

1.6.2 忘記密碼

1.6.2.1 mysql 5.5

  1. 可執行使用/usr/bin/mysqld_safe --user=mysql --skip-grant-tables &
[root@node01 ~]# /usr/bin/mysqld_safe --user=mysql --skip-grant-tables &
[1] 16638
[root@node01 ~]# 200603 06:27:49 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.
200603 06:27:49 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

[root@node01 ~]#
  1. 而後用mysql命令進入修改密碼:
[root@node01 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1
Server version: 5.5.65-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)]> update mysql.user set passwrod=password('') where user="root" and host="localhost";
ERROR 1054 (42S22): Unknown column 'passwrod' in 'field list'
MariaDB [(none)]> 
MariaDB [(none)]> 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
MariaDB [mysql]> update user set password=password('123') where user='root' and host='localhost';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [mysql]> 

MariaDB [mysql]> flush  privileges; 
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]>

1.6.2.2 mysql 5.7

  1. 編輯修改/etc/my.cnf
[root@node02 ~]# vim /etc/my.cnf
  1. 在[mysqld]中添加

skip-grant-tables

例如:

[mysqld]

skip-grant-tables

datadir=/data/mysql

socket=/temp/mysql.sock

  1. 重啓mysql
[root@node02 ~]# systemctl restart mysqld.service
  1. 用戶無密碼登陸
[root@node02 ~]# mysql -uroot -p (直接點擊回車,密碼爲空)
  1. 選擇數據庫
mysql> 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
mysql>
  1. 修改root密碼
mysql> update mysql.user set authentication_string=password('1qaz.#EDC') where user='root';
Query OK, 0 rows affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 1

mysql>
  1. 執行
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql>
  1. 退出 mysql
mysql> quit
Bye
[root@node02 ~]#
  1. 編輯 /etc/my.cnf

刪除 skip-grant-tables 保存退出

  1. 重啓mysql
[root@node02 ~]# systemctl restart mysqld.service
[root@node02 ~]#

1.7 安全設置

安裝完mysql,若是用於生產環境,最好執行mysql_secure_installation來作一些常規化安全設置。

1.7.1 設置密碼複雜度策略及密碼;

[root@node02 ~]# mysql_secure_installation

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: Y

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2
Please set the password for root here.

New password: 

Re-enter new password:

1.7.2 刪除匿名用戶;

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y                        
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
Success.

1.7.3 不容許遠程登陸;

Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
Success.

1.7.4 刪除測試數據庫;

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y

 - Dropping test database...
   Success.

 - Removing privileges on test database...
   Success.

1.7.5 刷新MySQL的系統權限相關表。

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.

All done!
相關文章
相關標籤/搜索