MariaDB基本操作

MariaDB的基本使用:

概述:

  1. mariadb是c/s架构的程序

    C:

    mysql:CLI交互式客户端程序;

    mysqldump, mysqladmin…

S:

mysqld_safe:默认启动使用

mysqld:普通

mysqld_multi:多进程mysql,类似虚拟主机一类

  1. 服务器监听的两种socket地址:
    1. ip socket: 监听在tcp的3306端口,支持远程通信;
    2. unix sock: 监听在sock文件上(/tmp/mysql.sock, /var/lib/mysql/mysql.sock),仅支持本地通信;只能server: localhost, 127.0.0.1
  1. 命令行交互式客户端程序:mysql

    mysql

    -uUSERNAME: 用户名;默认为root

    -hHOST: 服务器主机; 默认为localhost

    -pPASSWORD:用户的密码; 默认为空密码

    注意:mysql用户账号由两部分组成:’USERNAME’@’HOST’; 其中HOST用于限制此用户可通过哪些主机远程连接mysql服务;

    1. 支持使用通配符:

    %: 匹配任意长度的任意字符;

    172.16.0.0/16, 172.16.%.%

    _: 匹配任意单个字符:

    使用mysql默认连接为:

    [root@localhost mysql]# mysql -uroot -h 127.0.0.1

    [root@localhost mysql]# mysql -uroot -h localhost

    1. 例如:

mysql> use mysql

Database changed

mysql> SELECT User,Host,Password FROM user;

+——+———————–+———-+

| User | Host | Password |

+——+———————–+———-+

| root | localhost | |

| root | localhost.localdomain | |

| root | 127.0.0.1 | |

| root | ::1 | |

| | localhost | |

| | localhost.localdomain | |

+——+———————–+———-+

6 rows in set (0.00 sec)

  1. 需要安全初始化:

[root@localhost mysql]# /usr/local/mysql/bin/mysql_secure_installation

Set root password? [Y/n] y

Remove anonymous users? [Y/n] y

Disallow root login remotely? [Y/n] n 一般不允许root远程登陆

Remove test database and access to it? [Y/n] n

Reload privilege tables now? [Y/n] y

mysql> use mysql;

Database changed

mysql> SELECT User,Host,Password From user;

+——+———————–+——————————————-+

| User | Host | Password |

+——+———————–+——————————————-+

| root | localhost | *310AF8D67AE450FB86125F07FF75D1583528B45F |

| root | localhost.localdomain | *310AF8D67AE450FB86125F07FF75D1583528B45F |

| root | 127.0.0.1 | *310AF8D67AE450FB86125F07FF75D1583528B45F |

| root | ::1 | *310AF8D67AE450FB86125F07FF75D1583528B45F |

+——+———————–+——————————————-+

rows in set (0.02 sec)

现在安全了。

  1. 客户端命令:本地执行

mysql> help

每个命令都完整形式和简写格式;

mysql> HELP

For information about MySQL products and services, visit:

http://www.mysql.com/

For developer information, including the MySQL Reference Manual, visit:

http://dev.mysql.com/

To buy MySQL Enterprise support, training, or other products, visit:

https://shop.mysql.com/

List of all MySQL commands:

Note that all text commands must be first on line and end with ‘;’

? (\?) Synonym for `help’.

clear (\c) Clear the current input statement.

connect (\r) Reconnect to the server. Optional arguments are db and host.

delimiter (\d) Set statement delimiter.

edit (\e) Edit command with $EDITOR.

ego (\G) Send command to mysql server, display result vertically.

exit (\q) Exit mysql. Same as quit.

go (\g) Send command to mysql server.

help (\h) Display this help.

nopager (\n) Disable pager, print to stdout.

notee (\t) Don’t write into outfile.

pager (\P) Set PAGER [to_pager]. Print the query results via PAGER.

print (\p) Print current command.

prompt (\R) Change your mysql prompt.

quit (\q) Quit mysql.

rehash (\#) Rebuild completion hash.

source (\.) Execute an SQL script file. Takes a file name as an argument.

status (\s) Get status information from the server.

system (\!) Execute a system shell command.

tee (\T) Set outfile [to_outfile]. Append everything into given outfile.

use (\u) Use another database. Takes database name as argument.

charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.

warnings (\W) Show warnings after every statement.

nowarning (\w) Don’t show warnings after every statement.

        status, \s

  1. 服务端命令:通过mysql协议发往服务器执行并取回结果每个命令都必须命令结束符号;默认为分号;

例如:

mysql> SELECT VERSION();

+—————-+

| VERSION() |

+—————-+

| 5.5.54-MariaDB |

+—————-+

1 row in set (0.00 sec)

mysql> SELECT ‘1+1’;

+—–+

| 1+1 |

+—–+

| 1+1 |

+—–+

1 row in set (0.00 sec)

mysql> SELECT 1+1;

+—–+

| 1+1 |

+—–+

| 2 |

+—–+

1 row in set (0.03 sec)

  1. SQL语句:
    1. DDL: Data Defination Language

CREATE, DROP, ALTER

  1. DML: Data Manipulation Language

INSERT, DELETE, UPDATE, SELECT

  1. DCL:

    GRANT, REVOKE

CREATE

  1. 获取命令使用帮助:mysql> HELP KEYWORD;

mysql> HELP CREATE DATABASE;

CREATE、DROP

  1. 数据库
    1. 创建数据库:CREATE DATABASE|SCHEMA [IF NOT EXISTS] ‘DB_NAME’;
    1. CHARACTER SET ‘charecter set name’

mysql> CREATE DATABASE jiazi CHARACTER SET utf8;

Query OK, 1 row affected (0.00 sec)

  1. COLLATE ‘collate name’

mysql> CREATE DATABASE jiazi COLLATE utf8mb4_general_ci;

Query OK, 1 row affected (0.00 sec)

  1. IF NOT EXISTS

mysql> CREATE DATABASE IF NOT EXISTS jiazi CHARACTER SET utf8 ;

Query OK, 1 row affected (0.02 sec)

  1. 查看支持所有排序规则:SHOW COLLATIONS;

mysql> SHOW COLLATION;

utf8_general_ci | utf8 | 33 | Yes | Yes | 1 |

  1. 查看支持所有字符集:SHOW CHARACTER SET;

mysql> SHOW CHARACTER SET;

| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |

  1. 语法:DROP DATABASE|SCHEMA [IF EXISTS] ‘DB_NAME’;

mysql> DROP DATABASE jiazi;

  1. 表:CREATE TABLE、DROP TABLES
    1. 创建表:CREATE TABLE [IF NOT EXISTS] tb_name (col1 datatype 修饰符, col2 datatype 修饰符) ENGINE=”

    mysql> CREATE DATABASE IF NOT EXISTS jiazi CHARACTER SET utf8;

    Query OK, 1 row affected (0.00 sec)

    mysql> USE jiazi;

    Database changed

    mysql> CREATE TABLE IF NOT EXISTS tb1 (id INT NOT NULL,name VARCHAR(100) NOT NULL,age TINYINT);

    Query OK, 0 rows affected (0.07 sec)

    1. 删除表:DROP TABLE [IF EXISTS] tb_name;

    mysql> DROP TABLE IF EXISTS tb1;

    Query OK, 0 rows affected (0.02 sec)

    1. 查看所有的引擎:SHOW ENGINES;

mysql> SHOW ENGINES;

  1. 查看表:SHOW TABLES [FROM db_name]

mysql> SHOW TABLES FROM jiazi;

  1. 查看表结构:DESC [db_name.]tb_name

mysql> DESC tb1;

  1. 创建表:CREATE TABLE [IF NOT EXISTS] tb_name (col1 datatype 修饰符, col2 datatype 修饰符) ENGINE=”
    1. col type1
    2. PRIMARY KEY(col1,…)
    3. INDEX(col1, …)
    4. UNIQUE KEY(col1, …)

例如:

mysql> CREATE TABLE IF NOT EXISTS tb1(id INT UNSIGNED NOT NULL PRIMARY KEY,name VARCHAR(20) NOT NULL,age TINYINT );

Query OK, 0 rows affected (0.03 sec)

  1. 表选项:
    1. ENGINE [=] engine_name
    2. ROW_FORMAT[=]{DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT}

mysql> CREATE TABLE IF NOT EXISTS tb2 (id INT UNSIGNED NOT NULL PRIMARY KEY,name VARCHAR(20) NOT NULL UNIQUE KEY,age TINYINT NOT NULL) ENGINE InnoDB,ROW_FORMAT COMPRESSED;

Query OK, 0 rows affected, 2 warnings (0.03 sec)

  1. 查看创建命令:SHOW CREATE TABLE tbl_name;

mysql> SHOW CREATE TABLE tb2;

  1. 查看表状态:SHOW TABLE STATUS LIKE ‘tbl_name’\G

mysql> SHOW TABLE STATUS LIKE ‘tb2’\G

数据类型:

  1. 字符型
    1. 定长字符型:

      CHAR(#), 不区分大小写

      BINARY(#)区分大小写

    2. 变长字符型:

      VARCHAR(#),不区分大小写

      VARBINARY(#)区分大小写

  2. 对象存储:

    TEXT: 不区分大小写最大44g个字符

            BLOB:区分字符大小写,二进制格式存储

  3. 内置类型:

    ENUM:枚举类型的

    SET:集合式的

  4. 数值型
    1. 精确数值型
      1. 整型: int
        1. tinyint: 1byte
        2. smallint: 2bytes
        3. mediumint: 3bytes
        4. int: 4bytes
        5. bigint: 8bytes
      2. 十进制: decimal
    2. 近似数值型
      1. 单精度浮点型:float
      1. 双精度浮点型: double
  5. 日期时间型:

    日期:DATE

    时间:TIME

    日期时间:DATETIME

    时间戳:TIMESTAMP

    年份:YEAR(2), YEAR(4)

  6. 修饰符:
    1. 所有类型适用:

    NOT NULL:非空约束

    DEFAULT:设定默认值

            PRIMARY KEY :设为主键

    UNIQUE KEY :设为唯一健

    1. 数值型适用:

    UNSIGNED:正数

    AUTO_INCREMENT :自动增加

ALTER TABLE ‘tbl_name’

  1. 字段:
    1. 添加字段:add

ADD col1 data_type [FIRST|AFTER col_name]

mysql> ALTER TABLE tb2 ADD gender ENUM(‘M’,’F’) FIRST;

Query OK, 0 rows affected, 2 warnings (0.05 sec)

Records: 0 Duplicates: 0 Warnings: 2

  1. 删除字段:drop

mysql> ALTER TABLE tb1 DROP WEIGHT;

Query OK, 0 rows affected, 2 warnings (0.06 sec)

Records: 0 Duplicates: 0 Warnings: 2

  1. 修改字段:alter, change, modify
    1. Change:

mysql> ALTER TABLE tb2 CHANGE id sid INT UNSIGNED NOT NULL;

Query OK, 0 rows affected, 2 warnings (0.09 sec)

Records: 0 Duplicates: 0 Warnings: 2


  1. Alter:

mysql> ALTER TABLE tb1 ALTER weight SET DEFAULT 250;

Query OK, 0 rows affected (0.04 sec)

Records: 0 Duplicates: 0 Warnings: 0

  1. Modify

mysql> ALTER TABLE tb1 MODIFY AGE INT;

Query OK, 0 rows affected, 2 warnings (0.04 sec)

Records: 0 Duplicates: 0 Warnings: 2

  1. 索引与键:
    1. 主键有唯一性非空约束,唯一键只有唯一性约束,键一定是索引而索引不一定是键。
    2. 添加索引唯一键:add

    mysql> ALTER TABLE tb2 ADD UNIQUE KEY(age);

    Query OK, 0 rows affected (0.14 sec)

    Records: 0 Duplicates: 0 Warnings: 0

    1. 删除索引: drop

    mysql> ALTER TABLE tb2 DROP age;

    Query OK, 0 rows affected, 2 warnings (0.06 sec)

    Records: 0 Duplicates: 0 Warnings: 2


  2. 表选项
    1. 修改:

查看表上的索引:SHOW INDEXES FROM [db_name.]tbl_name;

mysql> SHOW INDEXES FROM tb2;

索引:

  1. 索引是特殊数据结构;定义在查找时作为查找条件的字段;
  2. 索引:要有索引名称;
  3. 创建索引:

CREATE INDEX index_name ON tbl_name (index_col_name,…);

mysql> CREATE INDEX test ON tb1(age);

Query OK, 0 rows affected (0.04 sec)

Records: 0 Duplicates: 0 Warnings: 0

  1. 删除索引:

DROP INDEX index_name ON tbl_name;

mysql> DROP INDEX name ON tb2;

Query OK, 0 rows affected (0.01 sec)

mysql> show indexes from tb2;

INSERT

INSERT INTO:

INSERT [INTO] tbl_name [(col_name,…)] {VALUES | VALUE} (val1,…),(…),…

例如:

mysql> INSERT INTO tb1 VALUES(‘m’,’1′,’Yang Guo’,28,75,180),(‘f’,’2′,’Guo Xiang’,’18’,’45’,’160′);

Query OK, 2 rows affected (0.00 sec)

Records: 2 Duplicates: 0 Warnings: 0

允许为空的可以不给定值:

mysql> INSERT INTO tb1(id,name,weight,high) VALUES(‘3′,’Guo Jing’,’50’,’180′),(‘4′,’Huang Rong’,’40’,’44’);

Query OK, 2 rows affected (0.03 sec)

Records: 2 Duplicates: 0 Warnings: 0

SELECT

SELECT col1,col2,… FROM tbl_name [WHERE clause] [ORDER BY ‘col_name’ [DESC]] [LIMIT [m,]n];

字段表示法:

*: 所有字段;

mysql> SELECT * FROM tb1;

as:字段别名,col1 AS alias1;

mysql> SELECT name as uname,AGE as age1 FROM tb1;

mysql> SELECT * FROM tb1 WHERE id=1

mysql> SELECT * FROM tb1 ORDER BY name;

mysql> SELECT * FROM tb1 ORDER BY name DESC;

mysql> SELECT * FROM tb1 ORDER BY name DESC LIMIT 2;

mysql> SELECT * FROM tb1 ORDER BY name DESC LIMIT 1,2;

WHERE clase:

  1. 操作符:
    1. >, <, >=, <=, ==, !=

mysql> SELECT * FROM tb1 WHERE gender=’m’;

  1. BETWEEN … AND …

mysql> SELECT * FROM tb1 WHERE id BETWEEN 2 and 4 ORDER BY name;

  1. LIKE:
    1. %:任意长度的任意字符;

mysql> SELECT * FROM tb1 WHERE name LIKE ‘G%’ ORDER BY name;

  1. _:任意单个字符;
  1. RLIKE:正则表达式模式匹配;

mysql> SELECT * FROM tb1 WHERE name RLIKE ‘[A-G].*J’;

mysql> SELECT * FROM tb1 WHERE name RLIKE ‘^[A-H].*’;

  1. IS NULL
  1. mysql> SELECT * FROM tb1 WHERE gender IS NULL; (非常影响资源,一般绝对不允许经常查找的值为空)

  1. IS NOT NULL
  1. 条件逻辑操作:

And

mysql> SELECT * FROM tb1 WHERE id>=2 and id<=4 ORDER BY name;

or

not

DELETE

DELETE FROM tbl_name [WHERE clause] [ORDER BY ‘col_name’ [DESC]] [LIMIT [m,]n];

mysql> DELETE FROM tb1 WHERE id >=2 LIMIT 1;

UPDATE

UPDATE tbl_name SET col1=new_val1, col2=new_val2, … [WHERE clause] [ORDER BY ‘col_name’ [DESC]] [LIMIT [m,]n];

mysql> UPDATE tb1 SET gender=’m’,AGE =’40’WHERE id =3 LIMIT 1;

用户账号及权限管理:

  1. 用户账号:’user’@’host’

user: 用户名

host: 此用户访问mysqld服务时允许通过哪些主机远程创建连接;

IP、网络地址、主机名、通配符(%和_);

  1. 禁止检查主机名:

my.cnf, [mysqld]

skip_name_resolve = yes

  1. 创建用户账号:CREATE USER ‘username’@’host’ [IDENTIFIED BY ‘password’];

mysql> CREATE USER ‘jiazi’@’172.16.31.125’ IDENTIFIED BY ‘cisco’;

  1. 删除用户:DROP USER ‘username’@’host’;

mysql> DROP USER ‘jiazi’@’172.16.31.124’;

Query OK, 0 rows affected (0.00 sec)

  1. 授权:权限级别:管理权限、数据库、表、字段、存储例程;

GRANT priv_type,… ON [object_type] db_name.tb_name TO ‘user’@’host’ [IDENTIFIED BY ‘password’] [WITH GRANT OPTION];

priv_type: ALL [PRIVILEGES]

db_name.tb_name:

*.*: 所有库的所表;

db_name.*: 指定库的所有表;

db_name.tb_name: 指定库的指定表;

db_name.routine_name:指定库的存储例程;

mysql> GRANT SELECT,DELETE ON jiazi.* TO ‘jiazi’@’172.16.31.124’ IDENTIFIED BY ‘cisco’;

Query OK, 0 rows affected (0.00 sec)

  1. 查看指定用户获得的授权:

    SHOW GRANTS FOR ‘user’@’host’;

    SHOW GRANTS FOR CURRENT_USER;

    MariaDB [(none)]> SHOW GRANTS FOR CURRENT_USER;


  1. 回收授权:

REVOKE priv_type, … ON db_name.tb_name FROM ‘user’@’host’;

mysql> REVOKE SELECT ON jiazi.* FROM ‘jiazi’@’172.16.31.124’;

Query OK, 0 rows affected (0.00 sec)

  1. 注意:MariaDB服务进程启动时会读取mysql库中的所有授权表至内存中;
    1. GRANT或REVOKE等执行权限操作会保存于表中,MariaDB的服务进程会自动重读授权表;
    2. 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:

mysql> FLUSH PRIVILEGES;

你可能感兴趣的:(MariaDB基本操作)