: colon
; semicolon
MySQL
SQL(Structured Query Language)
Features
- Open source(开源)
- Scalable(可伸缩)
- Portable(可移植)
- Works with client/server and embedded architecture(使用客户端/服务端嵌入式架构)
- High performance(高性能)
- Low TCO(低成本)
- Reliable(可靠)
- Easy to use(易于使用)
- Secure(安全)
- High availability(高可用性)
最小屏幕分辨率$1280\times 1024$, 推荐$1920\times 1200$及以上
Database Query Language
DDL
It is used to define and modify the structure the database objects, such as tables, views, and indexs.
数据定义语言(Data Definition Language, DDL):数据的模式定义和数据的物理存取构建。
- CREATE
- ALTER
- RENAME
- DROP
- TRUNCATE
DML
Is used to manipulate the data in database objects.
数据操纵语言(Data Manipulation Language, DML):负责数据的操纵,包括查询及增、删、改等操作。
- INSERT
- UPDATE
- DELETE
- SELECT
DCL
Is used to control the access to the objects in the database.
数据控制语言(Data Control Language, DCL):负责数据的完整性、安全性的定义与检查以及并发控制、故障恢复等功能。
- GRANT(to assign access permissions to the users on the database objects.)
- REVOKE(to deny permissions)
Layered architecture
Application layer
Administrative interface and utilities
Client interfaces and utilities
Query interface and utilities
Logical layer
Query processor subsystem
Transaction management subsystem
Recovery management subsystem
Storge management subsystem
储存引擎(Storage engines)
- InnoDB(default)
- MyISAM(supports full-text search indexs.)
- Memory(Nontransaction-safe storage engine, supports temporary tables types and stores tables in memory rather than in secondary storage devices.)
Physical layer
MySql登录
1 | mysql -P 端口号 -h mysql主机名\ip -u root(用户名) -p password dbname |
最简单1
mysql -u root -p
MySQL commands
1 | Help or \h or ? |
数据库
Database Objects
Table
A table contains data int rows and columns. It provides a structured organization of data. It offers a provision for maintaining data integrity by allowing users to:
Store only the data that satisfies certain pre-defined conditions.
Perform only those operations on the data that do not violate the conditions.
Index
An index is an internal table structure that MySQL uses to provide quick access to the rows of a table, based on the values of one or more columns. An index is similar to the index of a book.
View
A view is a virtual table that provides access to a subset of columns from one or more related tables.
Stored procedure
A stored procedure is a named block of SQL and procedural statements that are stored in the server and executed as a single unit.
Function
A function is a named block of SQL and procedural statements that are stored under one name and return a value.
Trigger
A trigger is a named object associated with a table, and comprises a block of SQL statements. A trigger is invoked automatically whenever an event on the assoociated table occurs.
Types of Databases
User-defined Databases
System Databases
- information_schema
- mysql
- performance_schema
建立数据库
1 | CREATE DATABASE [IF NOT EXISTS] <database_name> |
The default character in MySQL is latin1.
big5 supports the Chinese language.
使用数据库
1 | USE <database_name> |
修改数据库
1 | ALTER DATABASE <database_name> |
查询使用的character set1
SHOW CHARACTER SET;
删除数据库
1 | DROP DATABASE database_name; |
MySQL does not allow deleting system databases.
数据类型
Numeric
String
Date
Integer Data Types
Data type | Range for signed integers | Range for unsigned integers | Storage(Bytes) |
---|---|---|---|
TINYINT | -128 to 127 | 0 to 255 | 1 |
SMALLINT | -32,768 to 32,767 | 0 to 65535 | 2 |
MEDIUMINT | -83,88,608 to 83,88,607 | 0 to 16777215 | 3 |
INT / INTEGER | -2,147,483,648 to 2,147,483,647 | 0 to 4294967295 | 4 |
BIGINT | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0 to 18446744073709551615 | 8 |
Fractional Data Types
Data type | Range | Used to store | Storage(Bytes) |
---|---|---|---|
FLOAT | -3.402823466E+38 to -1.175494351E-38, 0 and 1.175494351E-38 to 3.402823466E+38 | Fractional value with floating single-precision | 4 |
DOUBLE(p,s) PRECISION(p,s) REAL(p,s) | -1.7976931348623157E+308 to -2.2250738585072014E-308, 0 and 2.2250738585072014E-308 to 1.7976931348623157E+308 | Fractional value with floating double- precision and scale | 8 |
DECIMAL(p,s) DEC(p,s) NUMERIC(p,s) FIXED(p,s) | Depends on values specified in the column definition | Fractional value with fixed precision and scale | NA |
Bit Data Type
BIT(M)
表示方法b’1001’
String
Data type | Range | Used to store |
---|---|---|
CHAR(n) | n characters, 1 <= n <= 255 | Fixed length |
VARCHAR(n) | n characters, 1 <=n <= 255 | Variable length |
TINYTEXT | 1 to 255 characters | Variable length |
TEXT | 1 to 65,535 characters | Variable length |
MEDIUMTEXT | 1 to 16,777,215 characters | Variable length |
LONGTEXT | 1 to 4,294,967,295 characters | Variable length |
BINARY(n) | n bytes, 1<= n <= 255 | Fixed length |
VARBINARY(N) | n bytes, 1<=n <= 255 | Variable length |
TINYBLOB | 255 characters(355 bytes) | Variable length |
BLOB | 1 to 65,535 characters(64KB) | Variable length |
MEDIUMBLOB | 1 to 16,777,215 characters(16MB) | Variable length |
LONGBLOB | 1 to 4,294,967,295 characters(4GB) | Variable length |
BLOB 类型可以储存图片
Date
Data type | Range | Used to store |
---|---|---|
DATE | 1000-01-01 through 9999-12-31 | Date data |
DATETIME | 1000-01-01 00:00:00 through 9999-12-31 23:59:59 | Date and time data |
TIMESTAMP | 1970-01-01 00:00:00 2037-12-31 | Date and time value that is updated with the current date and time value of system, whenever a record is updated or inserted into the table |
YEAR | 1901 to 2155 | Year data |
TIME | -838:59:59 to 838:59:59 | Time data |
ENUM
用一个数字index表示数据
eg.
1 | create table if not exists tb( |
Set
跟ENUM差不多,但是是个集合,取值为子集而不是用index
Eg.
1 | create table if not exists tb ( |
表格
创建表格
1 | CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table_name>(<column_definition> [{, <column_definition>}...]) |
查看表格属性1
2DESCRIBE table_name [column_name | `value`]
DESC Products 'P%'
查看是数据库中表格1
SHOW TABLES
添加约束
在创建表格时1
2
3[CONSTRAINT constraint_name] PRIMARY KEY(<column_name> [{, <column_name>}...])
[CONSTRAINT constraint_name] UNIQUE (<column_name> [{, <column_name>}...])
[CONSTRAINT constraint_name] FOREIGN KEY (<column_name> [{, <column_name>}...]) REFERENCES master_table_name(<column_name> [{,<column_name>}...])
修改表格
1 | ALTER TABLE <table_name> |
Manipulating Table Data
Inserting Data
INSERT Statement1
2
3
4
5
6INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] <table_name>
{<values_option> | <set_option>};
<values_option>=
SET <column_name>={<value_list> | DEFAULT}
[{, <column_name>={value_list> | DEFAULT}}...]
REPLACE Statement1
REPLACE [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] {<values_option> | <set_option>};
Updating Data
1 | UPDATE [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] <table_name> |
Copying Data
SELECT statement1
SELECT *|<column_name> [{,<column_name>}...] FROM <table_name>;
Copying data to an existing table1
2
3
4
5INSERT INTO <table_name>
SELECT *|<column_name> [{,<column_name>}...] FROM <table_name>;
or
REPLACE INTO <table_name>
SELECT *|<column_name> [{,<column_name>}...] FROM <table_name>;
Copying data to a new table1
2
3CREATE TABLE <table_name> (
<column_definition>[{, <column_definition>}...]
) SELECT *|<column_name> [{,<column_name>}...] FROM <table_name>;
Deleting Data
DELETE statement1
DELETE [LOW_PRIORITY] [IGNORE] FROM <table_name> [WHERE <condition>];
TRUNCATE statement
删除所有记录,相当于把表删除重建1
TRUNCATE [TALBE] <table_name>;
Removing a Table
1 | DROP [TEMPORARY] TALBE [IF EXISTS] [database_name].<table_name>[{,<table_name>}...] |
插入图片
long blob类型
1 | insert into commoditytable values('qiezibao', load_file('F:\\Code\\mysql\\a.jpg')); |
Retrieving Data 检索数据
Retrieving Specific Attributes
SELECT statement1
2SELECT [ALL|DISTINCT] select_expr[as new_name] [, select_expr...]
[FROM table_reference] [WHERE where_condition]
逻辑运算符
1 | OR(||) |
比较运算符
1 | > |
算术运算符
1 | DIV (整除) |
用LIMIT约束
1 | LIMIT [offset, ] row_count |
用函数Customize查询结果
String Functions
1 | ASCII |
1 | . matches a single character |
Date Functions
1 | ADDDATE |
expr1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16HOUR 小时
MINUTE 分
SECOND 秒
MICROSECOND 毫秒
YEAR 年
MONTH 月
DAY 日
WEEK 周
QUARTER 季
YEAR_MONTH 年和月
DAY_HOUR 日和小时
DAY_MINUTE 日和分钟
DAY_ SECOND 日和秒
HOUR_MINUTE 小时和分
HOUR_SECOND 小时和秒
MINUTE_SECOND 分钟和秒
1 | %a name of weekday in an abbreviate |
Mathematical Functions
1 | FLOOR |
Information Functions
1 | current_user() |
Cast Functions
1 | BINARY() # 大小写敏感 |
Aggregate Functions
1 | avg |
Sorting and Grouping Data
Sorting Data
1 | SELECT |
Grouping Data
1 | SELECT |
Join和Subqueries
Join
一张图片搞定
Inner Join
1 | SELECT column_name, column_name, [, column_name] |
ON 和 USING 二选一,USING可以合并相同的列
Outer Join
LEFT OUTER JOIN
RIGHT OUTER JOIN1
2
3
4
5SELECT column_name, column_name, [, column_name]
FROM table1_name [LEFT | RIGHT] OUTER JOIN table2_name
ON table1_name.ref_column_name join_operator
table2_name.ref_column_name | USING (ref_column_name)
[WHERE search_condition]
Natural Join
根据公共列连接两个表
A natural join clubs columns from one table with the columns of another table on the basis of a common column1
2SELECT column_name, column_name, [, column_name]
FROM <table_reference> NATURAL [{LEFT| RIGHT} [OUTER]] JOIN <table_reference>
Cross Join
A cross join is used to join each row of one table with each row of another table.
就是乘法1
2SELECT column_name, column_name, [, column_name]
FROM <table_reference> CROSS JOIN <table_reference>
Self Join
Compare the value of one column with that of another in the same table
In a self join a table is joined to itself. As a result, one row in a table correlates with other rows in the same table.1
2
3SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Subqueries
IN
1 | SELECT column, column [, column] |
EXISTS
1 | SELECT column, column [, column] |
1、exists是对外表做loop循环,每次loop循环再对内表(子查询)进行查询,那么因为对内表的查询使用的索引(内表效率高,故可用大表),而外表有多大都需要遍历,不可避免(尽量用小表),故内表大的使用exists,可加快效率;
2、in是把外表和内表做hash连接,先查询内表,再把内表结果与外表匹配,对外表使用索引(外表效率高,可用大表),而内表多大都需要查询,不可避免,故外表大的使用in,可加快效率。
3、如果用not in ,则是内外表都全表扫描,无索引,效率低,可考虑使用not exists,也可使用A left join B on A.id=B.id where B.id is null 进行优化。
Using Modified Comparison Operators
1 | SELECT column, column [, column] |
The ALL keyword returns a TRUE value if the comparison performed is true for all the values that are retrieved by the subquery. It return FALSE if only some of the values satisfy the comparison operator or if the subquery does not return any rows to the outer statement
The ANY keyword returns a TRUE value if any value retrieved by the subquery satisfies the comparison operator. It returns a FALSE value if no values in the subquery satisifies the comparison operator or if the subquery does not return any row that matches the outer statement.
Using Nested Subqueries
You may need to use one or more subqueries within another subquery, known as a nested subquery. In the nested subquery, the condition specified in a subquery depends on the result of another subquery, which, in turns depends on the result of some another subquery.
Using Correlated Subquery
相关子查询
1.扫描外查询的第一条记录
2.扫描子查询,并将第一条记录的对应值传给子查询,由此计算出子查询的结果
3.根据子查询的结果,返回外查询的结果。
4.重复上述动作,开始扫描外查询的第二条记录,第三条记录,直至全部扫描完毕
You may want to use an inner query that depends on the outer query for its execution.
In a normal nested subquery, the inner query executes only once. The main query is executed by using the value returned by the inner query.
On the other hand, in a correlated subquery, the inner query is driven by the outer query. In this case, the inner query executes once for each row seleted by the outer query.
Implementing Indexes and Views
Creating and Managing Indexes
Identifying the Types of Indexes
MySQL allows you to create indexes on the tables to speed up data access. Indexes should be created on the columns that are most frequently included in the conditions, such as the columns included in the WHERE
or HAVING
clauses of SELECT
statements. Therefore, you can create appropriate indexes on the required columns to improve the response time of the MySQL server.
MySQL supports the following types of indexes:
- Primary key
- Foreign key
- Unique
- Regular
- Full-text
Full-text index is defined on the column(s) that can accept string values. The purpose of this index is to improve the speed of the searches made on the string values included in the column data. The data type of the column(s) on which the full-text index can be defined can be
CHAR, VARCHAR, or TEXT
. Moreover, these column(s) can accept deplicate or NULL values.
The full-text indexes can be defined only on the tables that are accessed by using the MyISAM storage engine.
Creating Indexes
1 | CREATE TABLE <table_name> ( |
Viewing Indexes
1 | SHOW INDEXES FROM table_name [FROM database_name] |
Removing Indexes
1 | ALTER TABLE <table_name> |
Creating and Managing Views
A view is a database object that stores a query raised on one or more tables or other views. The query that contains joins, calculated columns, and subqueries is generally complex.
Views help in simplifying the execution of complex queries.
Creating Views
A view is a virtual table that provides access to subset of columns or records from one or more tables or views. In addition to the columns of tables or other views, a view definition can also contain calculated columns using aggregate functions. View is a query strored as an object in the database and does not have its own data. A view can derived are known as the base tables or underlying tables. A database developer can create views to ensure the security of data by restricting access to
- Specific records of a table.
- Specific columns of a table.
- Specific records and columns of a table.
- Records fetches by using joins.
- Subsets of other views or a subset of views and tables.
In addition to restricting access, views can also be used to create and save queries based on multiple tables.1
2
3CREATE [OR REPLACE]
VIEW view_name [(<column_name> [, <column_name>]...)]
AS <select_statment>
Querying Views
1 | SELECT <select_statment> FROM <view_name> [WHERE <where_condition>] |
View 可以包含 WHERE, ORDER BY, GROUP BY
Restrictions on Views
Some of these restriction are
- A view cannot be created on a temporary table.
- A temporary view cannot be created.
- A trigger cannot be created on a view.
- An index cannot be created on a view.
- The underlying table(s) or view(s) of view must already exist.
- The
SELECT
statement in a view definition cannot contain subqueries in theFROM
clause.
Updatable Views
The views are said to be non-updatable if the following constructs are contained in their defubutuib:
- An aggregate function in the column list.
- The
DISTINCT, GROUP BY, HAVING
clause in theSELECT
statement. - A subquery in the
SELECT
statement. - A nonupdatable view in the
FROM
clause.
Insert operations can be performed only on the views that contain all the NOT NULL columns from the underlying table(s) and do not contain any calculated column in the column list.
Update operation cannot bt performed on a view when
- It modifies the values of the derived columns.
- It results in modification of multiple tables.
MySQL allows you to perform the dalate operations only on those views that contain columns from a single table.
Managing Views
1 | ALTER [ALFORITHM = {UNDEFINED | MERGE | TEMPTABLE}] |
Implementing Compound Statements and Stored Routines
实现复合语句和储存过程
Creating a Compound Statement
复合语句1
2
3[begin_label:] BEGIN
[statement_list]
END [end_label]
变量
declare
1 | DECLARE var_name [, var_name] type [default values] |
set
1 | SET variable_assignment [, variable_assignment] |
声明与初始化
1 | # Local Variable 局部变量声明必须在begin end之间 |
函数
1 | delimiter // |
好像函数必须要有返回值…
流程控制语句
IF-THEN-ELSE
1 | IF condition THEN |
如果是elseif只需要一个end if; 如果是else if则需要两个
CASE
1 | CASE expression |
WHILE
1 | [loopname:] WHILE condition DO |
LOOP
1 | [begin_label:] LOOP |
LEAVE lable
可以跳出LOOP, REPEAT, WHILE
ITERATE statement
相当于continue1
ITERATE lable
REPEAT statement
1 | [begin_label:] REPEAT |
Handling Exceptions
1 | DECLARE handler_action HANDLER |
异常数值文档
https://dev.mysql.com/doc/refman/5.6/en/server-error-reference.html
返回异常1
2
3
4SIGNAL SQLSTATE [VALUE] sqlstate_value
[SET MESSAGE_TEXT=string_or_variable]
use '45000', which means “unhandled user-defined exception.”
Using Cursors
游标
In MySQL cursors can be used inside stored procedures, triggers, and functions. Folloewing steps:
- Declare a cursor 声明
- Open the cursor 打开
- Fetch the cursor 获取
- Close the curson 关闭
1 | DECLARE cursor_name CURSOR FOR select_statment |
Implementing Stored Routines
Procedures
1 | CREATE PROCEDURE proc_name ([[IN|OUT|INOUT]pro_parameter [, ...]]) |
IN
参数的值必须在调用存储过程时指定,在存储过程中修改该参数的值不能被返回,为默认值OUT
:该值可在存储过程内部被改变,并可返回INOUT
:调用时指定,并且可被改变和返回
Function
1 | CREATE FUNCTION func_name ([func_parameter[,..]]) RETURNS type |
Implementing Triggers and Transactions
Triggers
A triggers can be considered as small program that is pre-compiled and stored in the database. It is automatically executed when a DML statement, such as UPDATE, DELETE, or INSERT
is performed on the corresponding table.1
2
3
4
5
6
7
8
9CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER <trigger_name> <trigger_time> <trigger_event>
ON <table_name> FOR EACH ROW <trigger_body>
trigger_time:
AFER | BEFORE
trigger_event:
INSERT | UPDATE | DELETE
Restrictions on Triggers
- Any foreign key action does not activate triggers.
- The
CALL
statement is not permitted inside the trigger body. - A
TEMPORARY
table or a view cannot be associated with a trigger. - The
RETURN
statement is not permitted in trigger. - The
mysql
database does not permit any trigger creation on its tables. - Statement related to transactions such as
COMMIT, ROLLBACK, and START TRANSACTION
cannot be executed inside a trigger. - The trigger cache does not update itself dynamically if any changes are made to the structure of a database object after the information about its structure has been loaded in the cache.
用NEW | OLD
来区分, DELETE
里只有 OLD
.
1 | DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name |
Transactions
A transaction stands for a series of data manipulation statments encapsulated as a single logical unit of work. This single locical unit of work is executed in a specific sequence and its completion depends on the successful execution of each individual statement within it. If an individual statement fails, the entire logical unit of work will fail.
In an RDBMS, whenever an operation is performed, it can be treaded as a reansaction if it has ACID properties. These properties of a transaction can be explained as:
- Atomicity: This means that either all the data-rekated operations in a transaction atr performed or none of them is performed.
- Consistency: This means that all the data is in a consistent state after a transaction is completed successfully.
- Isolation: This delermines whether or not any changes in data by an operation atr made visible to a concurrent transaction.
Durability: This states that any change in data by a completed transaction remains permanently in effect in the system.
原子性:一个事务(transaction)中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
- 一致性:在事务开始之前和事务结束以后,数据库的完整性没有被破坏。这表示写入的资料必须完全符合所有的预设规则,这包含资料的精确度、串联性以及后续数据库可以自发性地完成预定的工作。
- 隔离性:数据库允许多个并发事务同时对其数据进行读写和修改的能力,隔离性可以防止多个事务并发执行时由于交叉执行而导致数据的不一致。事务隔离分为不同级别,包括读未提交(Read uncommitted)、读提交(read committed)、可重复读(repeatable read)和串行化(Serializable)。
- 持久性:事务处理结束后,对数据的修改就是永久的,即便系统故障也不会丢失。
1 | SET AUTOCOMMIT=0 禁止自动提交 |
事务的并发问题
1、脏读:事务A读取了事务B更新的数据,然后B回滚操作,那么A读取到的数据是脏数据
2、不可重复读:事务 A 多次读取同一数据,事务 B 在事务A多次读取的过程中,对数据作了更新并提交,导致事务A多次读取同一数据时,结果 不一致。
3、幻读:系统管理员A将数据库中所有学生的成绩从具体分数改为ABCDE等级,但是系统管理员B就在这个时候插入了一条具体分数的记录,当系统管理员A改结束后发现还有一条记录没有改过来,就好像发生了幻觉一样,这就叫幻读。
小结:不可重复读的和幻读很容易混淆,不可重复读侧重于修改,幻读侧重于新增或删除。解决不可重复读的问题只需锁住满足条件的行,解决幻读需要锁表
MySQL事务隔离级别
事务隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
读未提交(READ UNCOMMITTED) | 是 | 是 | 是 |
不可重复读(READ COMMITED) | 否 | 是 | 是 |
可重复读(REPEATABLE READ) | 否 | 否 | 是 |
串行化(SERIALIZABLE) | 否 | 否 | 否 |
Mysql 支持4种事务隔离级别. Mysql 默认的事务隔离级别为: REPEATABLE READ
a).read uncommitted(读未提交数据):允许事务读取未被其他事物提交的变更。脏读、不可重复读和幻读的问题都会出现
b).read commited(读已提交数据):只允许事务读取已经被其他事务提交的变更。可避免脏读,但不可重复读和幻读问题仍然存在
c).repeatable read(可重复读):确保事务可以多次从一个字段中读取相同的值,在这个事务持续期间,禁止其他事务对这个字段进行更新。可避免脏读和不可重复读,但幻读的问题仍然存在
d).serializable(串行化):确保事务可以从一个表中读取相同的行,在这个事务持续期间,禁止其他事务对该表执行增删改操作。所有的并发问题都可以避免,但性能什么低下。
READ UNCOMMITTED
The READ-UNCOMMITTED isolation level specifies that the transactions are able to see the data changes made by other transactions that atr not yet committed.
READ COMMITED
The READ-COMMITTED isolation level specifies that the data changes are visible to other transactions only when thay are committed.
REPEATABLE READ
The REPEATABLE-READ isolation level specifies that every read in the transaction will return the same set of data.
SERIALIZABLE
The SERIALIZABLE isolation level specifies that transactions place locks on all accessed records and the resource so that records cannot be added, updated, or deleted fron the table used in the transaction.
1 | SET [GOLBAL | SESSION] TRANSACTION ISOLATION LEVEL { |
Lock
MyISAM1
2
3
4
5
6
7LOCK {TABLE | TABLES}
<table_name> [AS <alias>] {READ [LOCAL] | [LOW_PRIORITY] WRITE}
[{, <table_name> [AS <alias>] {READ [LOCAL] | [LOW_PRIORITY] WRITE} }...]
UNLOCK {TABLE | TABLES}
SHOW OPEN TABLES;
导出和导入数据
导出数据
1 | select * from <tablename> into OUTFILE `<filename>` [<export_option>] |
貌似高版本无法导出文件,需要在MySQL安装路径里找my.ini,然后在[mysqld]后面加上一句,就能导出了
1 | [mysqld] |
导出csv
1 | select * from customertable |
导出图片
1 | select [select options] into dumpfile `<filename>`; |
导入数据
1 | LOAD DATA INFILE `<filename>` into table <tablename> [<import_option>] [IGNORE <number> LINES] [(<column name>[{, <column name>}...])] |
导入csv
1 | load data infile 'F:\\Code\\mysql\\a.csv' into table customertable |
Administering MySQL Databases
用户管理
创建用户
用sql语句有两种方法
一种create new user1
2create user 'joe' identified by 'password_joe';
create user 'joe'@'localhost' identified by 'password_joe';
一种insert into mysql.user1
insert into mysql.user values('%', 'beiyu', PASSWORD('beiyu'), 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', 0, 0, 0, 0, '', '');
用flush privileges;
刷新权限
hosts: localost = %
修改用户名
1 | rename user <old_user_name> to <new_user_name>; |
修改用户密码
两种方式,set password 和 update
1 | set password=password('1234'); # 修改当前账户密码 |
1 | update mysql.user set password=password('1234') where user 'beiyu'; |
删除用户
两种方式,drop user 和 delete1
2drop user account_name;
delete from user where user='beiyu';
用户权限管理
给予权限
1 | grant <privilege_type> [(<col_name> [, <col_name>...])] [, <privilege_type> [(<col_name> [, <col_name>...])] ...] |
privilege_type:
all
alter
create
create routine
create user
create view
delete
drop
select
update
privilege_level:
*.*
*
database_name.*
table_name
查看权限
1 | SHOW GRANT FOR account_name |
撤销权限
1 | REVOKE <privilege_type> [(<column_name>) [, <column_name>...]] |
备份
Back up
1 | mysqld --log-bin [=<base_name>] |
Recover
1 | mysql -u <user_name> -p [<database_name>] < <path_and_filename> |
Updating the Reloaded Databases Using Binary Logs
1 | mysqlbinlog "<Path>\<binary_log_file>" | mysql -u <user_name> -p |
Using Text File with Exported Binary Log Data1
mysqlbinlog "<Path>\<binary_log_file>" > "<Path>\<text_file>"