Home >headlines >Learn MySQL database in 1 hour

Learn MySQL database in 1 hour

阿神
阿神Original
2017-03-17 13:43:343018browse

With the end of the mobile Internet and the arrival of artificial intelligence, big data has become more and more important. The next winner should be one with massive data. You should know about data and databases.

1. Database overview

Database is a software system that stores and manages data, just like a logistics warehouse that stores data.

In the business field, information means business opportunities. A very important way to obtain information is to analyze and process data. This has given rise to various professional data management software, and database is one of them. Of course, the database management system was not established all at once. It has also undergone continuous enrichment and development to become what it is today.

1.1. Development history

1.1.1. Manual processing stage

In the early days of computers before the mid-1950s, their processing capabilities were very limited and could only complete some simple operations. Their data processing capabilities were also very limited, which made computers at that time only useful for scientific and engineering calculations. There is no special software for managing data on the computer. The data is carried by the computer or the program that processes it. When the data storage format, reading and writing paths, or methods change, the processing program must also make corresponding changes to maintain the correctness of the program.

1.1.2. File system

From the late 1950s to the mid-1960s, with the development of hardware and software technology, computers were not only used for scientific calculations, but also for commercial management. During this period, data and programs were completely separated in storage location, and data were organized into separate files and saved on external storage devices, so that the data files could be used by multiple different programs at different times.

Although programs and data are separated in storage locations, and the operating system can also help us manage the storage location and access paths of data, program design is still affected by the data storage format and method and cannot be completely independent of Data, and the data redundancy is large.

1.1.3. Database management system

Since the 1970s, computer software and hardware technology has achieved rapid development. The most important development during this period is the emergence of a true database management system, which enables a truly unified interface between applications and data. , data sharing, etc., so that applications can directly operate data in a unified manner, that is, applications and data have a high degree of independence.

Learn MySQL database in 1 hour

Figure 1: Tracing the development process of the database

1.2. Common database technology brands, services and architecture

After so many years of development, many database systems have appeared on the market. I personally think that the strongest one is Oracle. Of course, there are many more such as: DB2, Microsoft SQL Server, MySQL, SyBase, etc. The following figure lists common database technology brands, services and architectures. .

Learn MySQL database in 1 hour

Figure 2: Common database technology brands, services and architecture

1.3. Database classification

Databases are usually divided into three types: hierarchical databases, network databases and relational databases.

Different databases are related and organized according to different data structures.

In today's Internet, there are two main types of database models, namely relational databases and non-relational databases.

1.3.1. Relational database

Currently, the main database in mature applications and serving various systems is still a relational database.

Representative: Oracle, SQL Server, MySQL

1.3.2. Non-relational database

With the progress of the times and the needs of development, non-relational databases came into being.

Representative: Redis, Mongodb

NoSQL databases have advantages in storage speed and flexibility, and are often used for caching.

1.4. Database standardization

After a series of steps, we have finally converted the customer's needs into data tables and established the relationship between these tables. So can we use it in development now? The answer is no, why! For the same project, many people participated in the analysis of requirements and the design of the database. Different people have different ideas, and different departments have different business needs. The database we design based on this will inevitably contain a large amount of the same data. There may also be structural conflicts, causing inconvenience during development.

1.4.1. What is a paradigm

To design a standardized database, we are required to do it according to the database design paradigm - that is, the standardized principles of database design. The paradigm can guide us to better design the table structure of the database and reduce redundant data, thereby improving the storage efficiency, data integrity and scalability of the database.

When designing a relational database, follow different normative requirements to design a reasonable relational database. These different normative requirements are called different paradigms. Various paradigms present sub-standards. The higher the paradigm, the smaller the redundancy of the database. There are currently six normal forms of relational databases: first normal form (1NF), second normal form (2NF), third normal form (3NF), Badsko normal form (BCNF), fourth normal form (4NF) and fifth normal form (5NF). , also known as perfect paradigm). The normal form that meets the minimum requirements is first normal form (1NF). The one that further meets more normative requirements based on the first normal form is called the second normal form (2NF), and so on for the other normal forms. Generally speaking, the database only needs to meet the third normal form (3NF).

1.4.2. Three major paradigms

First Normal Form (1NF)

The so-called first normal form (1NF) refers to a specification requirement for adding columns in the relational model. All columns should be atomic, that is, each column of the database table is an indivisible atomic data item and cannot be Non-atomic data items such as collections, arrays, records, etc. That is, when an attribute in an entity has multiple values, it must be split into different attributes. Each field value in a first normal form (1NF) table can only be an attribute or part of an attribute of the entity. In short, first normal form is a domain without repetition.

For example: In Table 1-1, the "Project Address" column can also be subdivided into provinces, cities, etc. In foreign countries, more programs divide the "name" column into 2 columns, namely "surname" and "first name".

Although the first normal form requires that each column must be atomic and cannot be divided, this requirement is related to our needs. For example, in the above table, we do not have query and application requirements for "project address" such as provinces and cities. There is no need to split it, and the same is true for the "Name" column.

Table 1-1 Original table

Project number

Project name

Project Address

##Employee Number

Employee Name

Salary

Position

P001

Hong Kong-Zhuhai-Macao Bridge

Zhuhai, Guangdong

E0001

Jack

6000/month

Worker

P001

Hong Kong-Zhuhai-Macao Bridge

Zhuhai, Guangdong

E0002

Join

7800/month

Worker

P001

Hong Kong-Zhuhai-Macao Bridge

Zhuhai, Guangdong

E0003

Apple

8000/month

Senior Technician

P002

Nanhai Aerospace

Sanya, Hainan

E0001

Jack

5000/month

Worker

Second Normal Form (2NF)

On the basis of 1NF, non-Key attributes must completely depend on the primary key. The second normal form (2NF) is established on the basis of the first normal form (1NF), that is, to satisfy the second normal form (2NF), the first normal form (1NF) must be satisfied first. Second Normal Form (2NF) requires that each instance or record in a database table must be uniquely distinguishable. Select an attribute or attribute group that can distinguish each entity as the unique identifier of the entity.

Second Normal Form (2NF) requires that the attributes of an entity depend entirely on the primary key. The so-called complete dependence means that there cannot be an attribute that only depends on part of the primary key. If it exists, then this attribute and this part of the primary key should be separated to form a new entity. The new entity and the original entity are one-to-many. relation. To achieve differentiation, it is usually necessary to add a column to the table to store the unique identifier of each instance. In short, the second normal form is that the attributes completely depend on the primary key on the basis of the first normal form.

For example: In Table 1-1, a table describes project information, employee information, etc. This results in a large amount of data duplication. According to the second normal form, we can split Table 1-1 into Table 1-2 and Table 1-3:

l Project information table: (project number, project name, project address):

Table 1-2 Project information table

Project number

Project name

Project address

P001

Hong Kong-Zhuhai-Macao Bridge

Zhuhai, Guangdong

P002

Nanhai Aerospace

Sanya, Hainan

l Employee information table (employee number, employee name, position, salary level):

Table 1-3 Employee information table

Employee number

Employee name

Position

Salary level

E0001

Jack

Worker

3000/month

E0002

Join

Worker

3000/month

E0003

Apple

Senior Technician

6000/month

In this way, Table 1-1 becomes two tables, each table only describes one thing, clearly and clearly.

Third Normal Form (3NF)

The third normal form is based on the second normal form and goes one step further. The goal of the third normal form is to ensure that each column in the table is directly related to the primary key column, rather than indirectly. That is, each column has a direct dependency relationship with the primary key column, which satisfies the third normal form.

The third normal form requires that each column is directly related to the primary key column. We can understand it this way. Suppose Zhang San is Li Si's pawn, and Wang Wu is Zhang San's pawn. At this time, is Wang Wu the pawn of Li Si? From this relationship We can see that Wang Wu is also Li Si's soldier, because Wang Wu depends on Zhang San, and Zhang San is Li Si's soldier, so Wang Wu is also Li Si's soldier. There is an indirect dependence relationship rather than the direct dependence emphasized in our third paradigm.

Now let's take a look at the explanation of the second paradigm. We split Table 1-1 into two tables. Do these two tables conform to the third normal form? The employee information table contains: "employee number", "employee name", "position", "salary level", and we know that the salary level is determined by the position, here the "salary level" is related to the employee through the "position", It does not conform to the third normal form. We need to further split the employee information table as follows:

  • Employee information table: employee number, employee name, position

  • Job list: job number, job title, salary level

Now that we have understood the three major paradigms of database normalization design, let's take a look at the optimized data table of Table 1-1:

Employee Information Form (Employee)

Employee Number

Employee Name

Position number

E0001

Jack

1

E0002

Join

1

E0003

Apple

2

Project Information Table (ProjectInfo)

Project number

Project name

Project address

P001

Hong Kong-Zhuhai-Macao Bridge

Zhuhai, Guangdong

P002

Nanhai Aerospace

Sanya, Hainan

Duty List(Duty)

Duty Number

Duty Name

Wages

1

Worker

3000/month

2

Senior Technician

6000/month

Project participant record table (Project_ Employee_info)

Through comparison, we found that there are more tables, the relationships are more complex, it becomes more troublesome to query data, and the difficulty of programming has also increased. However, the content in each table is clearer, there is less duplicate data, and it is easier to update and maintain. Okay, how to balance this contradiction?

1.4.3. Paradigm and efficiency

When we design a database, designers, customers, and developers usually have certain conflicts about the design of the database. Customers prefer convenient and clear results, and developers also hope that database relationships will be simpler to reduce the difficulty of development, while designers need Apply three major paradigms to strictly standardize the database, reduce data redundancy, and improve database maintainability and scalability. It can be seen from this that in order to meet the three major paradigms, our database design will have differences with customers and developers. Therefore, in actual database design, we cannot blindly pursue standardization. We must consider the three major paradigms and reduce data redundancy. In case of abnormal operation of various databases, the performance issues of the database should be fully considered and appropriate database redundancy should be allowed.

2. Introduction to MySQL

2.1. MySQL overview

MySQL is a relational database management system developed by the Swedish MySQL AB company and is currently a product of Oracle. MySQL is one of the most popular relational database management systems. In terms of WEB applications, MySQL is one of the best RDBMS (Relational Database Management System) application software.

MySQL is a relational database management system. A relational database stores data in different tables instead of putting all data in one big warehouse, which increases speed and improves flexibility.

The SQL language used by MySQL is the most commonly used standardized language for accessing databases. MySQL software adopts a dual licensing policy and is divided into community version and commercial version. Due to its small size, fast speed, low total cost of ownership, and especially the characteristics of open source, MySQL is generally chosen as the website database for the development of small and medium-sized websites.

MySQL Download

2.2. System features

1. Written in C and C++ and tested using a variety of compilers to ensure source code portability.

2. Supports AIX, FreeBSD, HP-UX, Linux, Mac OS, NovellNetware, OpenBSD, OS/2 Wrap, Solaris, Windows and other operating systems.

3. APIs are provided for several programming languages. These programming languages ​​include C, C++, Python, Java, Perl, PHP, Eiffel, Ruby, .NET and Tcl, etc.

4. Supports multi-threading and makes full use of CPU resources.

5. Optimized SQL query algorithm effectively improves query speed.

6. It can be used as a standalone application in a client-server network environment, or it can be embedded in other software as a library.

7. Multi-language support is provided. Common encodings such as Chinese GB 2312, BIG5, Japanese Shift_JIS, etc. can be used as data table names and data column names.

8. Provides multiple database connection channels such as TCP/IP, ODBC and JDBC.

9. Provides management tools for managing, checking, and optimizing database operations.

10. Support large databases. Can handle large databases with tens of millions of records.

11. Supports multiple storage engines.

12.MySQL is open source, so you don’t need to pay extra.

13.MySQL uses the standard SQL data language form.

14.MySQL has good support for PHP, which is currently the most popular web development language.

15.MySQL can be customized and adopts the GPL protocol. You can modify the source code to develop your own MySQL system.

16. Online DDL/change functionality, data architecture supports dynamic applications and developer flexibility (new in 5.6)

17. Copy global transaction identifiers to support self-healing clusters (new in 5.6)

18. Replicate crash-free slave machines to improve availability (new in 5.6)

19. Copy multi-threaded slaves to improve performance (new in 5.6)

20.3x faster performance (new in 5.7)

21. New optimizer (new in 5.7)

22. Native JSON support (new in 5.7)

23.Multi-source replication (new in 5.7)

24.GIS spatial extension (new in 5.7)

2.3. Storage engine

MySQL database has prepared different engines according to the needs of the application. Different engines have different focuses. The differences are as follows:

MyISAM The default database engine before MySQL 5.0, the most commonly used. Has high insertion and query speed, but does not support transactions

InnoDB is the preferred engine for transactional databases. It supports ACID transactions and row-level locking. It has become the default database engine since MySQL 5.5

BDB originates from Berkeley DB, another option for transactional databases, supporting other transaction features such as Commit and Rollback

Memory is a storage engine that places all data in memory and has extremely high insertion, update and query efficiency. But it will occupy memory space proportional to the amount of data. And its contents will be lost when MySQL is restarted

Merge combines a certain number of MyISAM tables into a whole, which is very useful for very large-scale data storage\

Archive is ideal for storing large amounts of independent, historical data. Because they are not read often. Archive has efficient insertion speed, but its support for queries is relatively poor

Federated combines different MySQL servers to logically form a complete database. Very suitable for distributed applications

Cluster/NDB is a highly redundant storage engine that uses multiple data machines to jointly provide services to improve overall performance and security. Suitable for applications with large amounts of data and high security and performance requirements

CSV is a storage engine that logically separates data by commas. It creates a .csv file for each data table in the database subdirectory. This is a normal text file, with each line of data occupying one text line. The CSV storage engine does not support indexing.

BlackHole black hole engine, any data written will disappear, generally used to record binlog as a relay for replication

The EXAMPLE storage engine is a stub engine that does nothing. It is intended as an example in the MySQL source code to demonstrate how to start writing a new storage engine. Again, its main interest is to developers. EXAMPLE The storage engine does not support indexing.

In addition, MySQL's storage engine interface is well defined. Interested developers can write their own storage engines by reading the documentation.

Learn MySQL database in 1 hour

Figure 3: Comparison of database storage engines

3. Quickly install and run the MySQL database

MySQL has always been open source and free in the past. After being acquired by Oracle, there have been some changes: the previous versions were all free, the community version is open source and free under the GPL agreement, and the commercial version provides richer functions but charges a fee.

3.1. Use the green version

In order to use MySQL conveniently and quickly, I have prepared a green MySQL, which can be used directly after decompression without any configuration.

Unzip it directly after downloading:

Click to start PStart.exe. This is a small tool for customizing menus, used to organize resources.

There are two green versions of MySQL software 5.0 and 5.5

Navicat for MySQL is a database client management tool

The result after clicking to start PStart.exe is as follows:

Click to start the MySQL service and run Navicat for MySQL.

3.1.1. Set up mysql remote access

Execute the mysql command to enter the mysql command mode and execute the following SQL code

mysql> use mysql; 
mysql> GRANT ALL ON *.* TO admin@'%' IDENTIFIED BY 'admin' WITH GRANT OPTION;

#The meaning of this sentence is to allow any computer with an IP address (the % above means this) to use the admin account and password (admin) to access this MySQL Server
#You must add an account similar to this before you can log in remotely. The root account cannot log in remotely, it can only log in locally

3.1.2. Modify mysql user password

1.mysqladmin command

The format is as follows (USER is the username and PASSWORD is the new password):

mysqladmin -u USER -p password PASSWORD

After this command, you will be prompted to enter the original password. Once entered correctly, you can modify it.
For example, if the password of the root user is set to 123456, then

mysqladmin -u root -p password 123456

2.UPDATE user statement

This method must first log in to mysql with the root account, and then execute:

UPDATE user SET password=PASSWORD('123456') WHERE user='root';
FLUSH PRIVILEGES;

3.SET PASSWORD statement

This method also requires you to log in to mysql with the root command first, and then execute:

SET PASSWORD FOR root=PASSWORD('123456');

4. When the root password is lost

Use "MySQL GUI Tools", a tool that comes with MySQL. I have been using version 5.0. Run a program MySQLSystemTrayMonitor.exe in the installation directory. After running, an icon will appear in the system tray. If the MySQL service has not been installed, it will not appear. You can first configure and install the service through Action>Manage MySQL Instances. If the service has been installed, the "Configure Instance" menu will appear after right-clicking the mouse. After clicking, the following MySQL Administrator window appears:
If the original service configuration is normal, select "Startup Variables" in the list on the left, select "Security" in the corresponding label on the right, and check "Disable" grant table" and then "Apply changes".

And return to the "Server Control" on the left and the corresponding "Start/Stop Service" tab on the right, click Start Service. At this point, a username and password are no longer required to connect to mysql. You can change the root password.

3.1.2. Installation service

First, we first enter the bin directory under the mysql installation directory, then open the DOS command window and enter the directory (be sure to enter the directory, otherwise the operation will be incorrect)

Execute DOS command:

Enter the command: mysqld –install, and the following interface will appear. It prompts that the service installation is successful.

Note that it is mysqld –install not mysql –install

If you want to uninstall the service, you can enter the following command: mysqld –remove. The following interface appears. Prompt that the service was removed successfully.

3.2. Use the installation version

MySQL5.5.12 installation package

Select Custom:

Installed component information:

Server software directory:

Data directory:

Click install to install:

Configuration:

Machine type

Whether to support transaction function:

innodb table space:

Number of connections:

Character set setting:

Configuring windows management related:

Configure security options and set the administrator’s username and password:

Finally, execute the configuration:

After configuration, the service will be started.

The new version of MySQL installation package is much larger, and the installation process is also somewhat different.

4. Use GUI to operate MySQL

4.1. Typical concepts of relational database

Database databse: data warehouse

Table table: Data is stored in a table. Data stored in a table should have the same data format

Row: Row is used to record data

Record: Data within the row

Column: Column is used to specify the data format

Field: a column of data

SQL: A language used to manage data. Structured Query Language (SQL, Structured Query Language)

Primary key: uniquely identifies a record in the table, cannot be empty, cannot be repeated

4.2. Log in to the database

*You need to start the service when connecting to the local database

4.3. Create database

4.4. Create table

Column type:

Numeric type

Integer: tinyint, smallint, mediumint, int, bigint
Floating point number: float, double, real, decimal
Date and time: date, time, datetime, timestamp, year

String type
String: char, varchar
Text: tinytext, text, mediumtext, longtext

Binary (can be used to store pictures, music, etc.): tinyblob, blob, mediumblob, longblob

Column constraints:

Learn MySQL database in 1 hour

Figure 4: Database column constraints

4.5. Management data

4.5.1. Add data

Double-click the newly created table name to open the table and add data.

4.5.2. Delete data

4.5.3. Modify table structure

If you want to add a column to an existing table, you can modify the table structure:

4.5.4. Foreign key

There are some problems with the student table above:

a) It is not easy to modify. For example, if the classroom is changed to Classroom 305, each student will have to modify it

b), data redundancy, a large amount of duplicate data

Split the table into two and solve the problem after decomposition, as shown in the following figure:

The class number here is a foreign key and can be empty, but if it is not empty, its value must exist in the reference table. If the number in the student table is the primary key, it should not be repeated here. The foreign key can be repeated and is allowed to be empty.

Add foreign key:

Class table:

Student table:

Add foreign key:

Cascading updates and deletions can be achieved when deleting and updating. When the update is set to CASCADE, the primary key changes and the tables that reference the primary key will also change together. When the deletion is set to CASCADE, the primary key table is deleted and all referenced records will be deleted.

4.6. Computer practice

1. Please create a new database called HR and add the EMP table in the HR database. The table structure of the EMP table is as follows

EMP table, employee information

#Project No.

Personnel No.

1

P001

E0001

2

P001

E0002

3

## P002

E0003

## MGR int The leader number corresponding to the employee. The leader is also an employee and can be left empty (this column can be deleted) 5 6 7 8 9 Dept, department table

##Name

Type

Description

1

EMPNO

int

Employee number, primary key, auto-increment

2

ENAME

VARCHAR(10)

Employee's name, consisting of 10 characters, not empty, unique key

3

## JOB

VARCHAR(9)

Employee’s position

4

## HIREDATE

TimeStamp

The hire date of the employee, defaults to the current date

SAL

NUMBER(7,2)

Basic salary, which has two decimal places and five integers, a total of seven digits

## COMM

NUMBER(7,2)

Bonus, commission

DEPTNO

int

The department number of the employee, which can be empty, foreign key fk_deptno

DETAIL

Text

Remarks, can be empty

№## DTel VARCHAR(10) Phone number, can be left empty

##Name

Type

Description

1
DeptNO

int

Department number, primary key, automatically increased

2
DNAME

VARCHAR(10)

Department name, consisting of 50 characters, not empty, unique key

3

#

2. Complete the creation of the table based on the above table structure. The table name is emp

3. Add more than 5 pieces of data to the table

4. Complete the following query requirements

4.1 Query all employee information

4.2 Query the name, position and salary of all employees whose salary is between 2000-5000

4.3 Query all employees with the surname "Zhang"

4.4 Query the employees who joined from 2014 to 2015 in descending order of salary

4.5. Generally raise wages by 20%

4.6. Modify the bonus for employees whose salary is less than 3,000 yuan to 2.8 times the salary

4.7. Delete employees numbered 5 or whose surname is "Wang"

5. Use SQL to access MySQL database

5.1. Add data

The insert statement can be used to insert one or more rows of data into a database table. The general form used is as follows:

Insert into table name (field list) values ​​(value list);

insert [into] table name [(column name 1, column name 2, column name 3, ...)] values ​​(value 1, value 2, value 3, ...);

insert into students values(NULL, "Zhang San", "Male", 20, "18889009876");

Sometimes we only need to insert part of the data, or do not insert it in the order of the columns. We can insert it in this form:

insert into students (name, sex, age) values("李思", "女", 21);

5.2. Query data

The select statement is often used to obtain data from the database according to certain query rules. Its basic usage is:

select field name from table name [query condition];

Query all information in the students table: select * from students;

Query all name and age information in the student table: select name, age from students;

You can also use the wildcard * to query all the contents in the table, statement: select * from students;

5.2.1. Expressions and conditional queries

Learn MySQL database in 1 hour

Figure 5: Database operators

The where keyword is used to specify query conditions. The usage form is: select column name from table name where condition;

Take for example querying all information of female gender, enter the query statement: select * from students where sex="female";

The where clause not only supports the query form of "where column name = value" where the name is equal to the value, but also supports general comparison operators, such as =, >, =,

Example:

Query the information of everyone over the age of 21: select * from students where age > 21;

Query the information of everyone with the word "王" in their name: select * from students where name like "%王%";

Query the information of everyone whose id is less than 5 and age is greater than 20: select * from students where id20;

5.2.2. Aggregation function

Learn MySQL database in 1 hour

Figure 6: Common Group function

5.3. Delete data

delete from table name [delete condition];

Delete all data in the table: delete from students;

Delete the row with id 10: delete from students where id=10;

Delete all data whose age is less than 88 years old: delete from students where age

5.4. Update data

The update statement can be used to modify the data in the table. The basic usage form is:

update table name set column name = new value where update condition;

Update table name set field=value list update condition

Usage example:

Change the mobile phone number with id 5 to the default "-": update students set tel=default where id=5;

Increase everyone's age by 1: update students set age=age+1;

Change the name of the mobile phone number 13723887766 to “Zhang Guo” and the age to 19: update students set name=”Zhang Guo”, age=19 where tel=”13723887766″;

5.5. Modify table

The alter table statement is used to modify the table after creation. The basic usage is as follows:

5.5.1. Add column

Basic form: alter table table name add column name column data type [after insertion position];

Example:

Append the column address at the end of the table: alter table students add address char(60);

Insert the column birthday after the column named age: alter table students add birthday date after age;

5.5.2. Modify column

Basic form: alter table table name change column name column new name new data type;

Example:

Rename the table tel column to phone: alter table students change tel phone char(12) default “-”;

Change the data type of the name column to char(9): alter table students change name name char(9) not null;

5.5.3、删除列

基本形式: alter table 表名 drop 列名称;

示例:

删除 age 列: alter table students drop age;

5.5.4、重命名表

基本形式: alter table 表名 rename 新表名;

示例:

重命名 students 表为temp: alter table students rename temp;

5.5.5、删除表

基本形式: drop table 表名;

示例: 删除students表: drop table students;

5.5.6、删除数据库

基本形式: drop database 数据库名;

示例: 删除lcoa数据库: drop database lcoa;

5.5.7、一千行MySQL笔记

/* 启动MySQL */
net start mysql

/* 连接与断开服务器 */
mysql -h 地址 -P 端口 -u 用户名 -p 密码

/* 跳过权限验证登录MySQL */
mysqld --skip-grant-tables
-- 修改root密码
密码加密函数password()
update mysql.user set password=password('root');

SHOW PROCESSLIST -- 显示哪些线程正在运行
SHOW VARIABLES -- 

/* 数据库操作 */ ------------------
-- 查看当前数据库
    select database();
-- 显示当前时间、用户名、数据库版本
    select now(), user(), version();
-- 创建库
    create database[ if not exists] 数据库名 数据库选项
    数据库选项:
        CHARACTER SET charset_name
        COLLATE collation_name
-- 查看已有库
    show databases[ like 'pattern']
-- 查看当前库信息
    show create database 数据库名
-- 修改库的选项信息
    alter database 库名 选项信息
-- 删除库
    drop database[ if exists] 数据库名
        同时删除该数据库相关的目录及其目录内容

/* 表的操作 */ ------------------
-- 创建表
    create [temporary] table[ if not exists] [库名.]表名 ( 表的结构定义 )[ 表选项]
        每个字段必须有数据类型
        最后一个字段后不能有逗号
        temporary 临时表,会话结束时表自动消失
        对于字段的定义:
            字段名 数据类型 [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string']
-- 表选项
    -- 字符集
        CHARSET = charset_name
        如果表没有设定,则使用数据库字符集
    -- 存储引擎
        ENGINE = engine_name    
        表在管理数据时采用的不同的数据结构,结构不同会导致处理方式、提供的特性操作等不同
        常见的引擎:InnoDB MyISAM Memory/Heap BDB Merge Example CSV MaxDB Archive
        不同的引擎在保存表的结构和数据时采用不同的方式
        MyISAM表文件含义:.frm表定义,.MYD表数据,.MYI表索引
        InnoDB表文件含义:.frm表定义,表空间数据和日志文件
        SHOW ENGINES -- 显示存储引擎的状态信息
        SHOW ENGINE 引擎名 {LOGS|STATUS} -- 显示存储引擎的日志或状态信息
    -- 数据文件目录
        DATA DIRECTORY = '目录'
    -- 索引文件目录
        INDEX DIRECTORY = '目录'
    -- 表注释
        COMMENT = 'string'
    -- 分区选项
        PARTITION BY ... (详细见手册)
-- 查看所有表
    SHOW TABLES[ LIKE 'pattern']
    SHOW TABLES FROM 表名
-- 查看表机构
    SHOW CREATE TABLE 表名    (信息更详细)
    DESC 表名 / DESCRIBE 表名 / EXPLAIN 表名 / SHOW COLUMNS FROM 表名 [LIKE 'PATTERN']
    SHOW TABLE STATUS [FROM db_name] [LIKE 'pattern']
-- 修改表
    -- 修改表本身的选项
        ALTER TABLE 表名 表的选项
        EG:    ALTER TABLE 表名 ENGINE=MYISAM;
    -- 对表进行重命名
        RENAME TABLE 原表名 TO 新表名
        RENAME TABLE 原表名 TO 库名.表名    (可将表移动到另一个数据库)
        -- RENAME可以交换两个表名
    -- 修改表的字段机构
        ALTER TABLE 表名 操作名
        -- 操作名
            ADD[ COLUMN] 字段名        -- 增加字段
                AFTER 字段名            -- 表示增加在该字段名后面
                FIRST                -- 表示增加在第一个
            ADD PRIMARY KEY(字段名)    -- 创建主键
            ADD UNIQUE [索引名] (字段名)-- 创建唯一索引
            ADD INDEX [索引名] (字段名)    -- 创建普通索引
            ADD 
            DROP[ COLUMN] 字段名        -- 删除字段
            MODIFY[ COLUMN] 字段名 字段属性        -- 支持对字段属性进行修改,不能修改字段名(所有原有属性也需写上)
            CHANGE[ COLUMN] 原字段名 新字段名 字段属性        -- 支持对字段名修改
            DROP PRIMARY KEY    -- 删除主键(删除主键前需删除其AUTO_INCREMENT属性)
            DROP INDEX 索引名    -- 删除索引
            DROP FOREIGN KEY 外键    -- 删除外键

-- 删除表
    DROP TABLE[ IF EXISTS] 表名 ...
-- 清空表数据
    TRUNCATE [TABLE] 表名
-- 复制表结构
    CREATE TABLE 表名 LIKE 要复制的表名
-- 复制表结构和数据
    CREATE TABLE 表名 [AS] SELECT * FROM 要复制的表名
-- 检查表是否有错误
    CHECK TABLE tbl_name [, tbl_name] ... [option] ...
-- 优化表
    OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...
-- 修复表
    REPAIR [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ... [QUICK] [EXTENDED] [USE_FRM]
-- 分析表
    ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...

/* 数据操作 */ ------------------
-- 增
    INSERT [INTO] 表名 [(字段列表)] VALUES (值列表)[, (值列表), ...]
        -- 如果要插入的值列表包含所有字段并且顺序一致,则可以省略字段列表。
        -- 可同时插入多条数据记录!
        REPLACE 与 INSERT 完全一样,可互换。
    INSERT [INTO] 表名 SET 字段名=值[, 字段名=值, ...]
-- 查
    SELECT 字段列表 FROM 表名[ 其他子句]
        -- 可来自多个表的多个字段
        -- 其他子句可以不使用
        -- 字段列表可以用*代替,表示所有字段
-- 删
    DELETE FROM 表名[ 删除条件子句]
        没有条件子句,则会删除全部
-- 改
    UPDATE 表名 SET 字段名=新值[, 字段名=新值] [更新条件]

/* 字符集编码 */ ------------------
-- MySQL、数据库、表、字段均可设置编码
-- 数据编码与客户端编码不需一致
SHOW VARIABLES LIKE 'character_set_%'    -- 查看所有字符集编码项
    character_set_client        客户端向服务器发送数据时使用的编码
    character_set_results        服务器端将结果返回给客户端所使用的编码
    character_set_connection    连接层编码
SET 变量名 = 变量值
    set character_set_client = gbk;
    set character_set_results = gbk;
    set character_set_connection = gbk;
SET NAMES GBK;    -- 相当于完成以上三个设置
-- 校对集
    校对集用以排序
    SHOW CHARACTER SET [LIKE 'pattern']/SHOW CHARSET [LIKE 'pattern']    查看所有字符集
    SHOW COLLATION [LIKE 'pattern']        查看所有校对集
    charset 字符集编码        设置字符集编码
    collate 校对集编码        设置校对集编码

/* 数据类型(列类型) */ ------------------
1. 数值类型
-- a. 整型 ----------
    类型            字节        范围(有符号位)
    tinyint        1字节    -128 ~ 127        无符号位:0 ~ 255
    smallint    2字节    -32768 ~ 32767
    mediumint    3字节    -8388608 ~ 8388607
    int            4字节
    bigint        8字节

    int(M)    M表示总位数
    - 默认存在符号位,unsigned 属性修改
    - 显示宽度,如果某个数不够定义字段时设置的位数,则前面以0补填,zerofill 属性修改
        例:int(5)    插入一个数'123',补填后为'00123'
    - 在满足要求的情况下,越小越好。
    - 1表示bool值真,0表示bool值假。MySQL没有布尔类型,通过整型0和1表示。常用tinyint(1)表示布尔型。

-- b. 浮点型 ----------
    类型                字节        范围
    float(单精度)        4字节
    double(双精度)    8字节
    浮点型既支持符号位 unsigned 属性,也支持显示宽度 zerofill 属性。
        不同于整型,前后均会补填0.
    定义浮点型时,需指定总位数和小数位数。
        float(M, D)        double(M, D)
        M表示总位数,D表示小数位数。
        M和D的大小会决定浮点数的范围。不同于整型的固定范围。
        M既表示总位数(不包括小数点和正负号),也表示显示宽度(所有显示符号均包括)。
        支持科学计数法表示。
        浮点数表示近似值。

-- c. 定点数 ----------
    decimal    -- 可变长度
    decimal(M, D)    M也表示总位数,D表示小数位数。
    保存一个精确的数值,不会发生数据的改变,不同于浮点数的四舍五入。
    将浮点数转换为字符串来保存,每9位数字保存为4个字节。

2. 字符串类型
-- a. char, varchar ----------
    char    定长字符串,速度快,但浪费空间
    varchar    变长字符串,速度慢,但节省空间
    M表示能存储的最大长度,此长度是字符数,非字节数。
    不同的编码,所占用的空间不同。
    char,最多255个字符,与编码无关。
    varchar,最多65535字符,与编码有关。
    一条有效记录最大不能超过65535个字节。
        utf8 最大为21844个字符,gbk 最大为32766个字符,latin1 最大为65532个字符
    varchar 是变长的,需要利用存储空间保存 varchar 的长度,如果数据小于255个字节,则采用一个字节来保存长度,反之需要两个字节来保存。
    varchar 的最大有效长度由最大行大小和使用的字符集确定。
    最大有效长度是65532字节,因为在varchar存字符串时,第一个字节是空的,不存在任何数据,然后还需两个字节来存放字符串的长度,所以有效长度是64432-1-2=65532字节。
    例:若一个表定义为 CREATE TABLE tb(c1 int, c2 char(30), c3 varchar(N)) charset=utf8; 问N的最大值是多少? 答:(65535-1-2-4-30*3)/3

-- b. blob, text ----------
    blob 二进制字符串(字节字符串)
        tinyblob, blob, mediumblob, longblob
    text 非二进制字符串(字符字符串)
        tinytext, text, mediumtext, longtext
    text 在定义时,不需要定义长度,也不会计算总长度。
    text 类型在定义时,不可给default值

-- c. binary, varbinary ----------
    类似于char和varchar,用于保存二进制字符串,也就是保存字节字符串而非字符字符串。
    char, varchar, text 对应 binary, varbinary, blob.

3. 日期时间类型
    一般用整型保存时间戳,因为PHP可以很方便的将时间戳进行格式化。
    datetime    8字节    日期及时间        1000-01-01 00:00:00 到 9999-12-31 23:59:59
    date        3字节    日期            1000-01-01 到 9999-12-31
    timestamp    4字节    时间戳        19700101000000 到 2038-01-19 03:14:07
    time        3字节    时间            -838:59:59 到 838:59:59
    year        1字节    年份            1901 - 2155

datetime    “YYYY-MM-DD hh:mm:ss”
timestamp    “YY-MM-DD hh:mm:ss”
            “YYYYMMDDhhmmss”
            “YYMMDDhhmmss”
            YYYYMMDDhhmmss
            YYMMDDhhmmss
date        “YYYY-MM-DD”
            “YY-MM-DD”
            “YYYYMMDD”
            “YYMMDD”
            YYYYMMDD
            YYMMDD
time        “hh:mm:ss”
            “hhmmss”
            hhmmss
year        “YYYY”
            “YY”
            YYYY
            YY

4. 枚举和集合
-- 枚举(enum) ----------
enum(val1, val2, val3...)
    在已知的值中进行单选。最大数量为65535.
    枚举值在保存时,以2个字节的整型(smallint)保存。每个枚举值,按保存的位置顺序,从1开始逐一递增。
    表现为字符串类型,存储却是整型。
    NULL值的索引是NULL。
    空字符串错误值的索引值是0。

-- 集合(set) ----------
set(val1, val2, val3...)
    create table tab ( gender set('男', '女', '无') );
    insert into tab values ('男, 女');
    最多可以有64个不同的成员。以bigint存储,共8个字节。采取位运算的形式。
    当创建表时,SET成员值的尾部空格将自动被删除。

/* 选择类型 */
-- PHP角度
1. 功能满足
2. 存储空间尽量小,处理效率更高
3. 考虑兼容问题

-- IP存储 ----------
1. 只需存储,可用字符串
2. 如果需计算,查找等,可存储为4个字节的无符号int,即unsigned
    1) PHP函数转换
        ip2long可转换为整型,但会出现携带符号问题。需格式化为无符号的整型。
        利用sprintf函数格式化字符串
        sprintf("%u", ip2long('192.168.3.134'));
        然后用long2ip将整型转回IP字符串
    2) MySQL函数转换(无符号整型,UNSIGNED)
        INET_ATON('127.0.0.1') 将IP转为整型
        INET_NTOA(2130706433) 将整型转为IP

/* 列属性(列约束) */ ------------------
1. 主键
    - 能唯一标识记录的字段,可以作为主键。
    - 一个表只能有一个主键。
    - 主键具有唯一性。
    - 声明字段时,用 primary key 标识。
        也可以在字段列表之后声明
            例:create table tab ( id int, stu varchar(10), primary key (id));
    - 主键字段的值不能为null。
    - 主键可以由多个字段共同组成。此时需要在字段列表后声明的方法。
        例:create table tab ( id int, stu varchar(10), age int, primary key (stu, age));

2. unique 唯一索引(唯一约束)
    使得某字段的值也不能重复。

3. null 约束
    null不是数据类型,是列的一个属性。
    表示当前列是否可以为null,表示什么都没有。
    null, 允许为空。默认。
    not null, 不允许为空。
    insert into tab values (null, 'val');
        -- 此时表示将第一个字段的值设为null, 取决于该字段是否允许为null

4. default 默认值属性
    当前字段的默认值。
    insert into tab values (default, 'val');    -- 此时表示强制使用默认值。
    create table tab ( add_time timestamp default current_timestamp );
        -- 表示将当前时间的时间戳设为默认值。
        current_date, current_time

5. auto_increment 自动增长约束
    自动增长必须为索引(主键或unique)
    只能存在一个字段为自动增长。
    默认为1开始自动增长。可以通过表属性 auto_increment = x进行设置,或 alter table tbl auto_increment = x;

6. comment 注释
    例:create table tab ( id int ) comment '注释内容';

7. foreign key 外键约束
    用于限制主表与从表数据完整性。
    alter table t1 add constraint `t1_t2_fk` foreign key (t1_id) references t2(id);
        -- 将表t1的t1_id外键关联到表t2的id字段。
        -- 每个外键都有一个名字,可以通过 constraint 指定

    存在外键的表,称之为从表(子表),外键指向的表,称之为主表(父表)。

    作用:保持数据一致性,完整性,主要目的是控制存储在外键表(从表)中的数据。

    MySQL中,可以对InnoDB引擎使用外键约束:
    语法:
    foreign key (外键字段) references 主表名 (关联字段) [主表记录删除时的动作] [主表记录更新时的动作]
    此时需要检测一个从表的外键需要约束为主表的已存在的值。外键在没有关联的情况下,可以设置为null.前提是该外键列,没有not null。

    可以不指定主表记录更改或更新时的动作,那么此时主表的操作被拒绝。
    如果指定了 on update 或 on delete:在删除或更新时,有如下几个操作可以选择:
    1. cascade,级联操作。主表数据被更新(主键值更新),从表也被更新(外键值更新)。主表记录被删除,从表相关记录也被删除。
    2. set null,设置为null。主表数据被更新(主键值更新),从表的外键被设置为null。主表记录被删除,从表相关记录外键被设置成null。但注意,要求该外键列,没有not null属性约束。
    3. restrict,拒绝父表删除和更新。

    注意,外键只被InnoDB存储引擎所支持。其他引擎是不支持的。

/* 建表规范 */ ------------------
    -- Normal Format, NF
        - 每个表保存一个实体信息
        - 每个具有一个ID字段作为主键
        - ID主键 + 原子表
    -- 1NF, 第一范式
        字段不能再分,就满足第一范式。
    -- 2NF, 第二范式
        满足第一范式的前提下,不能出现部分依赖。
        消除符合主键就可以避免部分依赖。增加单列关键字。
    -- 3NF, 第三范式
        满足第二范式的前提下,不能出现传递依赖。
        某个字段依赖于主键,而有其他字段依赖于该字段。这就是传递依赖。
        将一个实体信息的数据放在一个表内实现。

/* select */ ------------------

select [all|distinct] select_expr from -> where -> group by [合计函数] -> having -> order by -> limit

a. select_expr
    -- 可以用 * 表示所有字段。
        select * from tb;
    -- 可以使用表达式(计算公式、函数调用、字段也是个表达式)
        select stu, 29+25, now() from tb;
    -- 可以为每个列使用别名。适用于简化列标识,避免多个列标识符重复。
        - 使用 as 关键字,也可省略 as.
        select stu+10 as add10 from tb;

b. from 子句
    用于标识查询来源。
    -- 可以为表起别名。使用as关键字。
        select * from tb1 as tt, tb2 as bb;
    -- from子句后,可以同时出现多个表。
        -- 多个表会横向叠加到一起,而数据会形成一个笛卡尔积。
        select * from tb1, tb2;

c. where 子句
    -- 从from获得的数据源中进行筛选。
    -- 整型1表示真,0表示假。
    -- 表达式由运算符和运算数组成。
        -- 运算数:变量(字段)、值、函数返回值
        -- 运算符:
            =, <=>, <>, !=, <=, <, >=, >, !, &&, ||, 
            in (not) null, (not) like, (not) in, (not) between and, is (not), and, or, not, xor
            is/is not 加上ture/false/unknown,检验某个值的真假
            <=>与<>功能相同,<=>可用于null比较

d. group by 子句, 分组子句
    group by 字段/别名 [排序方式]
    分组后会进行排序。升序:ASC,降序:DESC

    以下[合计函数]需配合 group by 使用:
    count 返回不同的非NULL值数目    count(*)、count(字段)
    sum 求和
    max 求最大值
    min 求最小值
    avg 求平均值
    group_concat 返回带有来自一个组的连接的非NULL值的字符串结果。组内字符串连接。

e. having 子句,条件子句
    与 where 功能、用法相同,执行时机不同。
    where 在开始时执行检测数据,对原数据进行过滤。
    having 对筛选出的结果再次进行过滤。
    having 字段必须是查询出来的,where 字段必须是数据表存在的。
    where 不可以使用字段的别名,having 可以。因为执行WHERE代码时,可能尚未确定列值。
    where 不可以使用合计函数。一般需用合计函数才会用 having
    SQL标准要求HAVING必须引用GROUP BY子句中的列或用于合计函数中的列。

f. order by 子句,排序子句
    order by 排序字段/别名 排序方式 [,排序字段/别名 排序方式]...
    升序:ASC,降序:DESC
    支持多个字段的排序。

g. limit 子句,限制结果数量子句
    仅对处理好的结果进行数量限制。将处理好的结果的看作是一个集合,按照记录出现的顺序,索引从0开始。
    limit 起始位置, 获取条数
    省略第一个参数,表示从索引0开始。limit 获取条数

h. distinct, all 选项
    distinct 去除重复记录
    默认为 all, 全部记录

/* UNION */ ------------------
    将多个select查询的结果组合成一个结果集合。
    SELECT ... UNION [ALL|DISTINCT] SELECT ...
    默认 DISTINCT 方式,即所有返回的行都是唯一的
    建议,对每个SELECT查询加上小括号包裹。
    ORDER BY 排序时,需加上 LIMIT 进行结合。
    需要各select查询的字段数量一样。
    每个select查询的字段列表(数量、类型)应一致,因为结果中的字段名以第一条select语句为准。

/* 子查询 */ ------------------
    - 子查询需用括号包裹。
-- from型
    from后要求是一个表,必须给子查询结果取个别名。
    - 简化每个查询内的条件。
    - from型需将结果生成一个临时表格,可用以原表的锁定的释放。
    - 子查询返回一个表,表型子查询。
    select * from (select * from tb where id>0) as subfrom where id>1;
-- where型
    - 子查询返回一个值,标量子查询。
    - 不需要给子查询取别名。
    - where子查询内的表,不能直接用以更新。
    select * from tb where money = (select max(money) from tb);
    -- 列子查询
        如果子查询结果返回的是一列。
        使用 in 或 not in 完成查询
        exists 和 not exists 条件
            如果子查询返回数据,则返回1或0。常用于判断条件。
            select column1 from t1 where exists (select * from t2);
    -- 行子查询
        查询条件是一个行。
        select * from t1 where (id, gender) in (select id, gender from t2);
        行构造符:(col1, col2, ...) 或 ROW(col1, col2, ...)
        行构造符通常用于与对能返回两个或两个以上列的子查询进行比较。

    -- 特殊运算符
    != all()    相当于 not in
    = some()    相当于 in。any 是 some 的别名
    != some()    不等同于 not in,不等于其中某一个。
    all, some 可以配合其他运算符一起使用。

/* 连接查询(join) */ ------------------
    将多个表的字段进行连接,可以指定连接条件。
-- 内连接(inner join)
    - 默认就是内连接,可省略inner。
    - 只有数据存在时才能发送连接。即连接结果不能出现空行。
    on 表示连接条件。其条件表达式与where类似。也可以省略条件(表示条件永远为真)
    也可用where表示连接条件。
    还有 using, 但需字段名相同。 using(字段名)

    -- 交叉连接 cross join
        即,没有条件的内连接。
        select * from tb1 cross join tb2;
-- 外连接(outer join)
    - 如果数据不存在,也会出现在连接结果中。
    -- 左外连接 left join
        如果数据不存在,左表记录会出现,而右表为null填充
    -- 右外连接 right join
        如果数据不存在,右表记录会出现,而左表为null填充
-- 自然连接(natural join)
    自动判断连接条件完成连接。
    相当于省略了using,会自动查找相同字段名。
    natural join
    natural left join
    natural right join

select info.id, info.name, info.stu_num, extra_info.hobby, extra_info.sex from info, extra_info where info.stu_num = extra_info.stu_id;

/* 导入导出 */ ------------------
select * into outfile 文件地址 [控制格式] from 表名;    -- 导出表数据
load data [local] infile 文件地址 [replace|ignore] into table 表名 [控制格式];    -- 导入数据
    生成的数据默认的分隔符是制表符
    local未指定,则数据文件必须在服务器上
    replace 和 ignore 关键词控制对现有的唯一键记录的重复的处理
-- 控制格式
fields    控制字段格式
默认:fields terminated by &#39;\t&#39; enclosed by &#39;&#39; escaped by &#39;\\&#39;
    terminated by &#39;string&#39;    -- 终止
    enclosed by &#39;char&#39;        -- 包裹
    escaped by &#39;char&#39;        -- 转义
    -- 示例:
        SELECT a,b,a+b INTO OUTFILE &#39;/tmp/result.text&#39;
        FIELDS TERMINATED BY &#39;,&#39; OPTIONALLY ENCLOSED BY &#39;"&#39;
        LINES TERMINATED BY &#39;\n&#39;
        FROM test_table;
lines    控制行格式
默认:lines terminated by &#39;\n&#39;
    terminated by &#39;string&#39;    -- 终止

/* insert */ ------------------
select语句获得的数据可以用insert插入。

可以省略对列的指定,要求 values () 括号内,提供给了按照列顺序出现的所有字段的值。
    或者使用set语法。
    insert into tbl_name set field=value,...;

可以一次性使用多个值,采用(), (), ();的形式。
    insert into tbl_name values (), (), ();

可以在列值指定时,使用表达式。
    insert into tbl_name values (field_value, 10+10, now());
可以使用一个特殊值 default,表示该列使用默认值。
    insert into tbl_name values (field_value, default);

可以通过一个查询的结果,作为需要插入的值。
    insert into tbl_name select ...;

可以指定在插入的值出现主键(或唯一索引)冲突时,更新其他非主键列的信息。
    insert into tbl_name values/set/select on duplicate key update 字段=值, …;

/* delete */ ------------------
DELETE FROM tbl_name [WHERE where_definition] [ORDER BY ...] [LIMIT row_count]

按照条件删除

指定删除的最多记录数。Limit

可以通过排序条件删除。order by + limit

支持多表删除,使用类似连接语法。
delete from 需要删除数据多表1,表2 using 表连接操作 条件。

/* truncate */ ------------------
TRUNCATE [TABLE] tbl_name
清空数据
删除重建表

区别:
1,truncate 是删除表再创建,delete 是逐条删除
2,truncate 重置auto_increment的值。而delete不会
3,truncate 不知道删除了几条,而delete知道。
4,当被用于带分区的表时,truncate 会保留分区

/* 备份与还原 */ ------------------
备份,将数据的结构与表内数据保存起来。
利用 mysqldump 指令完成。

-- 导出
1. 导出一张表
  mysqldump -u用户名 -p密码 库名 表名 > 文件名(D:/a.sql)
2. 导出多张表
  mysqldump -u用户名 -p密码 库名 表1 表2 表3 > 文件名(D:/a.sql)
3. 导出所有表
  mysqldump -u用户名 -p密码 库名 > 文件名(D:/a.sql)
4. 导出一个库 
  mysqldump -u用户名 -p密码 -B 库名 > 文件名(D:/a.sql)

可以-w携带备份条件

-- 导入
1. 在登录mysql的情况下:
  source  备份文件
2. 在不登录的情况下
  mysql -u用户名 -p密码 库名 < 备份文件

/* 视图 */ ------------------
什么是视图:
    视图是一个虚拟表,其内容由查询定义。同真实的表一样,视图包含一系列带有名称的列和行数据。但是,视图并不在数据库中以存储的数据值集形式存在。行和列数据来自由定义视图的查询所引用的表,并且在引用视图时动态生成。
    视图具有表结构文件,但不存在数据文件。
    对其中所引用的基础表来说,视图的作用类似于筛选。定义视图的筛选可以来自当前或其它数据库的一个或多个表,或者其它视图。通过视图进行查询没有任何限制,通过它们进行数据修改时的限制也很少。
    视图是存储在数据库中的查询的sql语句,它主要出于两种原因:安全原因,视图可以隐藏一些数据,如:社会保险基金表,可以用视图只显示姓名,地址,而不显示社会保险号和工资数等,另一原因是可使复杂的查询易于理解和使用。

-- 创建视图
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW view_name [(column_list)] AS select_statement
    - 视图名必须唯一,同时不能与表重名。
    - 视图可以使用select语句查询到的列名,也可以自己指定相应的列名。
    - 可以指定视图执行的算法,通过ALGORITHM指定。
    - column_list如果存在,则数目必须等于SELECT语句检索的列数

-- 查看结构
    SHOW CREATE VIEW view_name 

-- 删除视图
    - 删除视图后,数据依然存在。
    - 可同时删除多个视图。
    DROP VIEW [IF EXISTS] view_name ...

-- 修改视图结构
    - 一般不修改视图,因为不是所有的更新视图都会映射到表上。
    ALTER VIEW view_name [(column_list)] AS select_statement

-- 视图作用
    1. 简化业务逻辑
    2. 对客户端隐藏真实的表结构

-- 视图算法(ALGORITHM)
    MERGE        合并
        将视图的查询语句,与外部查询需要先合并再执行!
    TEMPTABLE    临时表
        将视图执行完毕后,形成临时表,再做外层查询!
    UNDEFINED    未定义(默认),指的是MySQL自主去选择相应的算法。

/* 事务(transaction) */ ------------------
事务是指逻辑上的一组操作,组成这组操作的各个单元,要不全成功要不全失败。 
    - 支持连续SQL的集体成功或集体撤销。
    - 事务是数据库在数据晚自习方面的一个功能。
    - 需要利用 InnoDB 或 BDB 存储引擎,对自动提交的特性支持完成。
    - InnoDB被称为事务安全型引擎。

-- 事务开启
    START TRANSACTION; 或者 BEGIN;
    开启事务后,所有被执行的SQL语句均被认作当前事务内的SQL语句。
-- 事务提交
    COMMIT;
-- 事务回滚
    ROLLBACK;
    如果部分操作发生问题,映射到事务开启前。

-- 事务的特性
    1. 原子性(Atomicity)
        事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。
    2. 一致性(Consistency)
        事务前后数据的完整性必须保持一致。
        - 事务开始和结束时,外部数据一致
        - 在整个事务过程中,操作是连续的
    3. 隔离性(Isolation)
        多个用户并发访问数据库时,一个用户的事务不能被其它用户的事物所干扰,多个并发事务之间的数据要相互隔离。
    4. 持久性(Durability)
        一个事务一旦被提交,它对数据库中的数据改变就是永久性的。

-- 事务的实现
    1. 要求是事务支持的表类型
    2. 执行一组相关的操作前开启事务
    3. 整组操作完成后,都成功,则提交;如果存在失败,选择回滚,则会回到事务开始的备份点。

-- 事务的原理
    利用InnoDB的自动提交(autocommit)特性完成。
    普通的MySQL执行语句后,当前的数据提交操作均可被其他客户端可见。
    而事务是暂时关闭“自动提交”机制,需要commit提交持久化数据操作。

-- 注意
    1. 数据定义语言(DDL)语句不能被回滚,比如创建或取消数据库的语句,和创建、取消或更改表或存储的子程序的语句。
    2. 事务不能被嵌套

-- 保存点
    SAVEPOINT 保存点名称 -- 设置一个事务保存点
    ROLLBACK TO SAVEPOINT 保存点名称 -- 回滚到保存点
    RELEASE SAVEPOINT 保存点名称 -- 删除保存点

-- InnoDB自动提交特性设置
    SET autocommit = 0|1;    0表示关闭自动提交,1表示开启自动提交。
    - 如果关闭了,那普通操作的结果对其他客户端也不可见,需要commit提交后才能持久化数据操作。
    - 也可以关闭自动提交来开启事务。但与START TRANSACTION不同的是,
        SET autocommit是永久改变服务器的设置,直到下次再次修改该设置。(针对当前连接)
        而START TRANSACTION记录开启前的状态,而一旦事务提交或回滚后就需要再次开启事务。(针对当前事务)

/* 锁表 */
表锁定只用于防止其它客户端进行不正当地读取和写入
MyISAM 支持表锁,InnoDB 支持行锁
-- 锁定
    LOCK TABLES tbl_name [AS alias]
-- 解锁
    UNLOCK TABLES

/* 触发器 */ ------------------
    触发程序是与表有关的命名数据库对象,当该表出现特定事件时,将激活该对象
    监听:记录的增加、修改、删除。

-- 创建触发器
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt
    参数:
    trigger_time是触发程序的动作时间。它可以是 before 或 after,以指明触发程序是在激活它的语句之前或之后触发。
    trigger_event指明了激活触发程序的语句的类型
        INSERT:将新行插入表时激活触发程序
        UPDATE:更改某一行时激活触发程序
        DELETE:从表中删除某一行时激活触发程序
    tbl_name:监听的表,必须是永久性的表,不能将触发程序与TEMPORARY表或视图关联起来。
    trigger_stmt:当触发程序激活时执行的语句。执行多个语句,可使用BEGIN...END复合语句结构

-- 删除
DROP TRIGGER [schema_name.]trigger_name

可以使用old和new代替旧的和新的数据
    更新操作,更新前是old,更新后是new.
    删除操作,只有old.
    增加操作,只有new.

-- 注意
    1. 对于具有相同触发程序动作时间和事件的给定表,不能有两个触发程序。

-- 字符连接函数
concat(str1[, str2,...])

-- 分支语句
if 条件 then
    执行语句
elseif 条件 then
    执行语句
else
    执行语句
end if;

-- 修改最外层语句结束符
delimiter 自定义结束符号
    SQL语句
自定义结束符号

delimiter ;        -- 修改回原来的分号

-- 语句块包裹
begin
    语句块
end

-- 特殊的执行
1. 只要添加记录,就会触发程序。
2. Insert into on duplicate key update 语法会触发:
    如果没有重复记录,会触发 before insert, after insert;
    如果有重复记录并更新,会触发 before insert, before update, after update;
    如果有重复记录但是没有发生更新,则触发 before insert, before update
3. Replace 语法 如果有记录,则执行 before insert, before delete, after delete, after insert

/* SQL编程 */ ------------------

--// 局部变量 ----------
-- 变量声明
    declare var_name[,...] type [default value] 
    这个语句被用来声明局部变量。要给变量提供一个默认值,请包含一个default子句。值可以被指定为一个表达式,不需要为一个常数。如果没有default子句,初始值为null。 

-- 赋值
    使用 set 和 select into 语句为变量赋值。

    - 注意:在函数内是可以使用全局变量(用户自定义的变量)

--// 全局变量 ----------
-- 定义、赋值
set 语句可以定义并为变量赋值。
set @var = value;
也可以使用select into语句为变量初始化并赋值。这样要求select语句只能返回一行,但是可以是多个字段,就意味着同时为多个变量进行赋值,变量的数量需要与查询的列数一致。
还可以把赋值语句看作一个表达式,通过select执行完成。此时为了避免=被当作关系运算符看待,使用:=代替。(set语句可以使用= 和 :=)。
select @var:=20;
select @v1:=id, @v2=name from t1 limit 1;
select * from tbl_name where @var:=30;

select into 可以将表中查询获得的数据赋给变量。
    -| select max(height) into @max_height from tb;

-- 自定义变量名
为了避免select语句中,用户自定义的变量与系统标识符(通常是字段名)冲突,用户自定义变量在变量名前使用@作为开始符号。
@var=10;

    - 变量被定义后,在整个会话周期都有效(登录到退出)

--// 控制结构 ----------
-- if语句
if search_condition then 
    statement_list    
[elseif search_condition then
    statement_list]
...
[else
    statement_list]
end if;

-- case语句
CASE value WHEN [compare-value] THEN result
[WHEN [compare-value] THEN result ...]
[ELSE result]
END

-- while循环
[begin_label:] while search_condition do
    statement_list
end while [end_label];

- 如果需要在循环内提前终止 while循环,则需要使用标签;标签需要成对出现。

    -- 退出循环
        退出整个循环 leave
        退出当前循环 iterate
        通过退出的标签决定退出哪个循环

--// 内置函数 ----------
-- 数值函数
abs(x)            -- 绝对值 abs(-10.9) = 10
format(x, d)    -- 格式化千分位数值 format(1234567.456, 2) = 1,234,567.46
ceil(x)            -- 向上取整 ceil(10.1) = 11
floor(x)        -- 向下取整 floor (10.1) = 10
round(x)        -- 四舍五入去整
mod(m, n)        -- m%n m mod n 求余 10%3=1
pi()            -- 获得圆周率
pow(m, n)        -- m^n
sqrt(x)            -- 算术平方根
rand()            -- 随机数
truncate(x, d)    -- 截取d位小数

-- 时间日期函数
now(), current_timestamp();     -- 当前日期时间
current_date();                    -- 当前日期
current_time();                    -- 当前时间
date(&#39;yyyy-mm-dd hh:ii:ss&#39;);    -- 获取日期部分
time(&#39;yyyy-mm-dd hh:ii:ss&#39;);    -- 获取时间部分
date_format(&#39;yyyy-mm-dd hh:ii:ss&#39;, &#39;%d %y %a %d %m %b %j&#39;);    -- 格式化时间
unix_timestamp();                -- 获得unix时间戳
from_unixtime();                -- 从时间戳获得时间

-- 字符串函数
length(string)            -- string长度,字节
char_length(string)        -- string的字符个数
substring(str, position [,length])        -- 从str的position开始,取length个字符
replace(str ,search_str ,replace_str)    -- 在str中用replace_str替换search_str
instr(string ,substring)    -- 返回substring首次在string中出现的位置
concat(string [,...])    -- 连接字串
charset(str)            -- 返回字串字符集
lcase(string)            -- 转换成小写
left(string, length)    -- 从string2中的左边起取length个字符
load_file(file_name)    -- 从文件读取内容
locate(substring, string [,start_position])    -- 同instr,但可指定开始位置
lpad(string, length, pad)    -- 重复用pad加在string开头,直到字串长度为length
ltrim(string)            -- 去除前端空格
repeat(string, count)    -- 重复count次
rpad(string, length, pad)    --在str后用pad补充,直到长度为length
rtrim(string)            -- 去除后端空格
strcmp(string1 ,string2)    -- 逐字符比较两字串大小

-- 流程函数
case when [condition] then result [when [condition] then result ...] [else result] end   多分支
if(expr1,expr2,expr3)  双分支。

-- 聚合函数
count()
sum();
max();
min();
avg();
group_concat()

-- 其他常用函数
md5();
default();

--// 存储函数,自定义函数 ----------
-- 新建
    CREATE FUNCTION function_name (参数列表) RETURNS 返回值类型
        函数体

    - 函数名,应该合法的标识符,并且不应该与已有的关键字冲突。
    - 一个函数应该属于某个数据库,可以使用db_name.funciton_name的形式执行当前函数所属数据库,否则为当前数据库。
    - 参数部分,由"参数名"和"参数类型"组成。多个参数用逗号隔开。
    - 函数体由多条可用的mysql语句,流程控制,变量声明等语句构成。
    - 多条语句应该使用 begin...end 语句块包含。
    - 一定要有 return 返回值语句。

-- 删除
    DROP FUNCTION [IF EXISTS] function_name;

-- 查看
    SHOW FUNCTION STATUS LIKE &#39;partten&#39;
    SHOW CREATE FUNCTION function_name;

-- 修改
    ALTER FUNCTION function_name 函数选项

--// 存储过程,自定义功能 ----------
-- 定义
存储存储过程 是一段代码(过程),存储在数据库中的sql组成。
一个存储过程通常用于完成一段业务逻辑,例如报名,交班费,订单入库等。
而一个函数通常专注与某个功能,视为其他程序服务的,需要在其他语句中调用函数才可以,而存储过程不能被其他调用,是自己执行 通过call执行。

-- 创建
CREATE PROCEDURE sp_name (参数列表)
    过程体

参数列表:不同于函数的参数列表,需要指明参数类型
IN,表示输入型
OUT,表示输出型
INOUT,表示混合型

注意,没有返回值。

/* 存储过程 */ ------------------
存储过程是一段可执行性代码的集合。相比函数,更偏向于业务逻辑。
调用:CALL 过程名
-- 注意
- 没有返回值。
- 只能单独调用,不可夹杂在其他语句中

-- 参数
IN|OUT|INOUT 参数名 数据类型
IN        输入:在调用过程中,将数据输入到过程体内部的参数
OUT        输出:在调用过程中,将过程体处理完的结果返回到客户端
INOUT    输入输出:既可输入,也可输出

-- 语法
CREATE PROCEDURE 过程名 (参数列表)
BEGIN
    过程体
END

/* 用户和权限管理 */ ------------------
用户信息表:mysql.user
-- 刷新权限
FLUSH PRIVILEGES
-- 增加用户
CREATE USER 用户名 IDENTIFIED BY [PASSWORD] 密码(字符串)
    - 必须拥有mysql数据库的全局CREATE USER权限,或拥有INSERT权限。
    - 只能创建用户,不能赋予权限。
    - 用户名,注意引号:如 &#39;user_name&#39;@&#39;192.168.1.1&#39;
    - 密码也需引号,纯数字密码也要加引号
    - 要在纯文本中指定密码,需忽略PASSWORD关键词。要把密码指定为由PASSWORD()函数返回的混编值,需包含关键字PASSWORD
-- 重命名用户
RENAME USER old_user TO new_user
-- 设置密码
SET PASSWORD = PASSWORD(&#39;密码&#39;)    -- 为当前用户设置密码
SET PASSWORD FOR 用户名 = PASSWORD(&#39;密码&#39;)    -- 为指定用户设置密码
-- 删除用户
DROP USER 用户名
-- 分配权限/添加用户
GRANT 权限列表 ON 表名 TO 用户名 [IDENTIFIED BY [PASSWORD] &#39;password&#39;]
    - all privileges 表示所有权限
    - *.* 表示所有库的所有表
    - 库名.表名 表示某库下面的某表
-- 查看权限
SHOW GRANTS FOR 用户名
    -- 查看当前用户权限
    SHOW GRANTS; 或 SHOW GRANTS FOR CURRENT_USER; 或 SHOW GRANTS FOR CURRENT_USER();
-- 撤消权限
REVOKE 权限列表 ON 表名 FROM 用户名
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 用户名    -- 撤销所有权限
-- 权限层级
-- 要使用GRANT或REVOKE,您必须拥有GRANT OPTION权限,并且您必须用于您正在授予或撤销的权限。
全局层级:全局权限适用于一个给定服务器中的所有数据库,mysql.user
    GRANT ALL ON *.*和 REVOKE ALL ON *.*只授予和撤销全局权限。
数据库层级:数据库权限适用于一个给定数据库中的所有目标,mysql.db, mysql.host
    GRANT ALL ON db_name.*和REVOKE ALL ON db_name.*只授予和撤销数据库权限。
表层级:表权限适用于一个给定表中的所有列,mysql.talbes_priv
    GRANT ALL ON db_name.tbl_name和REVOKE ALL ON db_name.tbl_name只授予和撤销表权限。
列层级:列权限适用于一个给定表中的单一列,mysql.columns_priv
    当使用REVOKE时,您必须指定与被授权列相同的列。
-- 权限列表
ALL [PRIVILEGES]    -- 设置除GRANT OPTION之外的所有简单权限
ALTER    -- 允许使用ALTER TABLE
ALTER ROUTINE    -- 更改或取消已存储的子程序
CREATE    -- 允许使用CREATE TABLE
CREATE ROUTINE    -- 创建已存储的子程序
CREATE TEMPORARY TABLES        -- 允许使用CREATE TEMPORARY TABLE
CREATE USER        -- 允许使用CREATE USER, DROP USER, RENAME USER和REVOKE ALL PRIVILEGES。
CREATE VIEW        -- 允许使用CREATE VIEW
DELETE    -- 允许使用DELETE
DROP    -- 允许使用DROP TABLE
EXECUTE        -- 允许用户运行已存储的子程序
FILE    -- 允许使用SELECT...INTO OUTFILE和LOAD DATA INFILE
INDEX     -- 允许使用CREATE INDEX和DROP INDEX
INSERT    -- 允许使用INSERT
LOCK TABLES        -- 允许对您拥有SELECT权限的表使用LOCK TABLES
PROCESS     -- 允许使用SHOW FULL PROCESSLIST
REFERENCES    -- 未被实施
RELOAD    -- 允许使用FLUSH
REPLICATION CLIENT    -- 允许用户询问从属服务器或主服务器的地址
REPLICATION SLAVE    -- 用于复制型从属服务器(从主服务器中读取二进制日志事件)
SELECT    -- 允许使用SELECT
SHOW DATABASES    -- 显示所有数据库
SHOW VIEW    -- 允许使用SHOW CREATE VIEW
SHUTDOWN    -- 允许使用mysqladmin shutdown
SUPER    -- 允许使用CHANGE MASTER, KILL, PURGE MASTER LOGS和SET GLOBAL语句,mysqladmin debug命令;允许您连接(一次),即使已达到max_connections。
UPDATE    -- 允许使用UPDATE
USAGE    -- “无权限”的同义词
GRANT OPTION    -- 允许授予权限

/* 表维护 */
-- 分析和存储表的关键字分布
ANALYZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE 表名 ...
-- 检查一个或多个表是否有错误
CHECK TABLE tbl_name [, tbl_name] ... [option] ...
option = {QUICK | FAST | MEDIUM | EXTENDED | CHANGED}
-- 整理数据文件的碎片
OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...

/* 杂项 */ ------------------
1. 可用反引号(`)为标识符(库名、表名、字段名、索引、别名)包裹,以避免与关键字重名!中文也可以作为标识符!
2. 每个库目录存在一个保存当前数据库的选项文件db.opt。
3. 注释:
    单行注释 # 注释内容
    多行注释 /* 注释内容 */
    单行注释 -- 注释内容        (标准SQL注释风格,要求双破折号后加一空格符(空格、TAB、换行等))
4. 模式通配符:
    _    任意单个字符
    %    任意多个字符,甚至包括零字符
    单引号需要进行转义 \&#39;
5. CMD命令行内的语句结束符可以为 ";", "\G", "\g",仅影响显示结果。其他地方还是用分号结束。delimiter 可修改当前对话的语句结束符。
6. SQL对大小写不敏感
7. 清除已有语句:\c

5.5.8、常用的SQL

/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2017/3/5 10:29:05                            */
/*==============================================================*/

drop table if exists Address;

drop table if exists ArticleComment;

drop table if exists ArticleType;

drop table if exists Articles;

drop table if exists DictSub;

drop table if exists DictTop;

drop table if exists OrderPdt;

drop table if exists Orders;

drop table if exists ProductComment;

drop table if exists Products;

drop table if exists Users;

/*==============================================================*/
/* Table: Address                                               */
/*==============================================================*/
create table Address
(
   `AddressId` int not null auto_increment comment &#39;收货地址编号&#39;,
   `UserId` int not null comment &#39;用户编号&#39;,
   `Province` varchar(50) not null comment &#39;省&#39;,
   `City` varchar(50) not null comment &#39;市&#39;,
   `County` varchar(50) not null comment &#39;县/区&#39;,
   `Street` varchar(300) not null comment &#39;详细地址&#39;,
   `RevName` varchar(30) not null comment &#39;收货人姓名&#39;,
   `PostCode` varchar(20) comment &#39;邮政编码&#39;,
   `Mobile` varchar(50) not null comment &#39;手机&#39;,
   `Phone` varchar(50) comment &#39;电话&#39;,
   `IsDefault` bool comment &#39;是否为默认地址&#39;,
   primary key (AddressId)
);

alter table Address comment &#39;收货地址&#39;;

/*==============================================================*/
/* Table: ArticleComment                                        */
/*==============================================================*/
create table ArticleComment
(
   `ArticleCommentId` int not null auto_increment comment &#39;文章评论编号&#39;,
   `ArticleId` int not null comment &#39;文章编号&#39;,
   `UserId` int not null comment &#39;用户编号&#39;,
   `ArticleCommentContent` varchar(4000) not null comment &#39;文章评论内容&#39;,
   `ArticleCommentDate` timestamp default CURRENT_TIMESTAMP comment &#39;文章评论时间&#39;,
   `ArticleCommentState` int default 1 comment &#39;状态&#39;,
   `ArticleRemark` int comment &#39;打分&#39;,
   `ArticleCommentReserver1` varchar(4000) comment &#39;备用1&#39;,
   `ArticleCommentReserver2` varchar(4000) comment &#39;备用2&#39;,
   primary key (ArticleCommentId)
);

alter table ArticleComment comment &#39;文章评论&#39;;

/*==============================================================*/
/* Table: ArticleType                                           */
/*==============================================================*/
create table ArticleType
(
   `ArticleTypeId` int not null auto_increment comment &#39;文章栏目编号&#39;,
   `ArticleTypeName` varchar(200) comment &#39;文章栏目名称&#39;,
   `ArticleTypeState` int default 1 comment &#39;状态&#39;,
   `ArticleTypeDesc` varchar(4000) comment &#39;文章栏目描述&#39;,
   `ArticleTypePicture` varchar(400) comment &#39;文章栏目图片&#39;,
   `ArticleTypeReserve1` varchar(4000) comment &#39;备用1&#39;,
   `ArticleTypeReserve2` varchar(4000) comment &#39;备用2&#39;,
   primary key (ArticleTypeId)
);

alter table ArticleType comment &#39;文章栏目&#39;;

/*==============================================================*/
/* Table: Articles                                              */
/*==============================================================*/
create table Articles
(
   `ArticleId` int not null auto_increment comment &#39;文章编号&#39;,
   `ArticleTypeId` int not null comment &#39;文章栏目编号&#39;,
   `ArticleTitle` varchar(400) not null comment &#39;文章标题&#39;,
   `ArticleContent` text comment &#39;文章内容&#39;,
   `ArticleDate` timestamp default CURRENT_TIMESTAMP comment &#39;文章发布时间&#39;,
   `ArticleAuthor` varchar(200) comment &#39;文章发布者&#39;,
   `ArticleFileName` varchar(100) comment &#39;静态文件名&#39;,
   `ArticleThumbNail` varchar(200) comment &#39;缩略图片&#39;,
   `ArticleAddition` varchar(200) comment &#39;附件名称&#39;,
   `ArticleLevel` int comment &#39;显示的优先级&#39;,
   `ArticleIsAllowComment` integer default 1 comment &#39;是否允许评论&#39;,
   `ArticleState` int default 1 comment &#39;状态&#39;,
   `ArticleHotCount` int comment &#39;点击次数&#39;,
   `ArticleReserve1` varchar(4000) comment &#39;备用1&#39;,
   `ArticleReserve2` varchar(4000) comment &#39;备用2&#39;,
   `ArticleReserve3` numeric(8,0) comment &#39;备用3&#39;,
   primary key (ArticleId)
);

alter table Articles comment &#39;文章&#39;;

/*==============================================================*/
/* Table: DictSub                                               */
/*==============================================================*/
create table DictSub
(
   `SubId` int not null auto_increment comment &#39;子项编号&#39;,
   `DictId` int not null comment &#39;字典编号&#39;,
   `SubName` varchar(200) not null comment &#39;子项名称&#39;,
   `SubDesc` varchar(4000) comment &#39;子项描述&#39;,
   `SubReserve1` varchar(4000) comment &#39;保留备用1&#39;,
   primary key (SubId)
);

alter table DictSub comment &#39;字典子项&#39;;

/*==============================================================*/
/* Table: DictTop                                               */
/*==============================================================*/
create table DictTop
(
   `DictId` int not null auto_increment comment &#39;字典编号&#39;,
   `DictName` varchar(100) not null comment &#39;字典名称&#39;,
   `DictDesc` varchar(4000) comment &#39;字典描述&#39;,
   `DictReserve1` varchar(4000) comment &#39;保留备用&#39;,
   primary key (DictId)
);

alter table DictTop comment &#39;字典&#39;;

/*==============================================================*/
/* Table: OrderPdt                                              */
/*==============================================================*/
create table OrderPdt
(
   `OrderPdtId` int not null auto_increment comment &#39;订单商品编号&#39;,
   `Id` int not null comment &#39;编号&#39;,
   `UserId` int not null comment &#39;用户编号&#39;,
   `OrderId` int comment &#39;订单号&#39;,
   `PdtAmount` int comment &#39;订购数量&#39;,
   `PdtPrice` decimal comment &#39;单价&#39;,
   `PdtReserve1` varchar(2000) comment &#39;备用1&#39;,
   `PdtReserve2` varchar(4000) comment &#39;备用2&#39;,
   primary key (OrderPdtId)
);

alter table OrderPdt comment &#39;订单商品&#39;;

/*==============================================================*/
/* Table: Orders                                                */
/*==============================================================*/
create table Orders
(
   `OrderId` int not null auto_increment comment &#39;订单号&#39;,
   `AddressId` int not null comment &#39;收货地址编号&#39;,
   `OrderState` int default 1 comment &#39;订单状态&#39;,
   `ExpressNO` varchar(50) comment &#39;快递编号&#39;,
   `ExpressName` varchar(50) comment &#39;快递名称&#39;,
   `PayMoney` decimal comment &#39;应支付&#39;,
   `PayedMoney` decimal comment &#39;已支付&#39;,
   `SendInfo` varchar(300) comment &#39;发货人信息&#39;,
   `BuyDate` timestamp default CURRENT_TIMESTAMP comment &#39;下单时间&#39;,
   `PayDate` datetime comment &#39;支付时间&#39;,
   `SendDate` datetime comment &#39;发货时间&#39;,
   `ReceivDate` datetime comment &#39;收货时间&#39;,
   `OrderMessage` varchar(4000) comment &#39;附言&#39;,
   `UserId` integer comment &#39;用户编号&#39;,
   `OrderReserve1` varchar(4000) comment &#39;备用1&#39;,
   `OrderReserve2` varchar(4000) comment &#39;备用2&#39;,
   `OrderReserve3` decimal comment &#39;备用3&#39;,
   primary key (OrderId)
);

alter table Orders comment &#39;订单&#39;;

/*==============================================================*/
/* Table: ProductComment                                        */
/*==============================================================*/
create table ProductComment
(
   `ProductCommentId` int not null auto_increment comment &#39;商品评论编号&#39;,
   `ProductId` int not null comment &#39;商品编号&#39;,
   `UserId` int not null comment &#39;用户编号&#39;,
   `ProductCommentContent` varchar(4000) comment &#39;商品评论内容&#39;,
   `ProductCommentDate` timestamp default CURRENT_TIMESTAMP comment &#39;商品评论时间&#39;,
   `ProductCommentState` int comment &#39;状态&#39;,
   `ProductCommentRemark` int comment &#39;打分&#39;,
   `ProductCommentReserve1` varchar(4000) comment &#39;备用1&#39;,
   `ProductCommentReserve2` varchar(4000) comment &#39;备用2&#39;,
   primary key (ProductCommentId)
);

alter table ProductComment comment &#39;商品评论&#39;;

/*==============================================================*/
/* Table: Products                                              */
/*==============================================================*/
create table Products
(
   `Id` int not null auto_increment comment &#39;编号&#39;,
   `Name` varchar(200) not null comment &#39;名称&#39;,
   `SubIdColor` int not null comment &#39;所属颜色&#39;,
   `SubIdBrand` int not null comment &#39;所属品牌&#39;,
   `SubIdInlay` int not null comment &#39;所属镶嵌&#39;,
   `SubIdMoral` int not null comment &#39;所属寓意&#39;,
   `SubIdMaterial` int not null comment &#39;所属种水&#39;,
   `SubIdTopLevel` int not null comment &#39;一级分类编号&#39;,
   `MarketPrice` decimal comment &#39;市场参考价&#39;,
   `MyPrice` decimal not null comment &#39;玉源直销价&#39;,
   `Discount` decimal default 1 comment &#39;折扣&#39;,
   `Picture` varchar(200) comment &#39;图片&#39;,
   `Amount` int comment &#39;库存量&#39;,
   `Description` text comment &#39;详细描述&#39;,
   `State` int default 1 comment &#39;状态&#39;,
   `AddDate` timestamp default CURRENT_TIMESTAMP comment &#39;上货日期&#39;,
   `Hang` int comment &#39;挂件&#39;,
   `RawStone` int comment &#39;赌石&#39;,
   `Size` varchar(200) comment &#39;尺寸&#39;,
   `ExpressageName` varchar(100) comment &#39;快递名称&#39;,
   `Expressage` decimal comment &#39;快递费&#39;,
   `AllowComment` int default 1 comment &#39;是否允许评论&#39;,
   `Reserve1` varchar(4000) comment &#39;保留备用1&#39;,
   `Reserve2` varchar(4000) comment &#39;保留备用2&#39;,
   `Reserve3` decimal(0) comment &#39;保留备用3&#39;,
   primary key (Id)
);

alter table Products comment &#39;商品&#39;;

/*==============================================================*/
/* Table: Users                                                 */
/*==============================================================*/
create table Users
(
   `UserId` int not null auto_increment comment &#39;用户编号&#39;,
   `UserName` varchar(200) not null comment &#39;用户名&#39;,
   `Password` varchar(512) not null comment &#39;密码&#39;,
   `Email` varchar(100) not null comment &#39;邮箱&#39;,
   `Sex` varchar(10) comment &#39;性别&#39;,
   `State` int default 1 comment &#39;状态&#39;,
   `RightCode` int comment &#39;权限状态&#39;,
   `RegDate` timestamp default CURRENT_TIMESTAMP comment &#39;注册时间&#39;,
   `RegIP` varchar(200) comment &#39;注册IP&#39;,
   `LastLoginDate` datetime comment &#39;最近登录时间&#39;,
   `UserReserve1` varchar(4000) comment &#39;保留备用1&#39;,
   `UserReserve2` varchar(4000) comment &#39;保留备用2&#39;,
   `UserReserve3` varchar(4000) comment &#39;保留备用3&#39;,
   primary key (UserId)
);

alter table Users comment &#39;用户&#39;;

alter table Address add constraint FK_AddressBelongUser foreign key (UserId)
      references Users (UserId) on delete restrict on update restrict;

alter table ArticleComment add constraint FK_ArticleCommentForArticle foreign key (ArticleId)
      references Articles (ArticleId) on delete restrict on update restrict;

alter table ArticleComment add constraint FK_ArticleCommentForUser foreign key (UserId)
      references Users (UserId) on delete restrict on update restrict;

alter table Articles add constraint FK_ArticleBelongType foreign key (ArticleTypeId)
      references ArticleType (ArticleTypeId) on delete restrict on update restrict;

alter table DictSub add constraint FK_BelongDict foreign key (DictId)
      references DictTop (DictId) on delete cascade on update cascade;

alter table OrderPdt add constraint FK_BelongOrder foreign key (OrderId)
      references Orders (OrderId) on delete cascade on update cascade;

alter table OrderPdt add constraint FK_CartForUser foreign key (UserId)
      references Users (UserId) on delete restrict on update restrict;

alter table OrderPdt add constraint FK_OrderDepProduct foreign key (Id)
      references Products (Id) on delete restrict on update restrict;

alter table Orders add constraint FK_OrderBelongAddress foreign key (AddressId)
      references Address (AddressId) on delete restrict on update restrict;

alter table ProductComment add constraint FK_ProductCommentBelongUsers foreign key (UserId)
      references Users (UserId) on delete restrict on update restrict;

alter table ProductComment add constraint FK_ProductCommentForProduct foreign key (ProductId)
      references Products (Id) on delete restrict on update restrict;

alter table Products add constraint FK_BelongBrand foreign key (SubIdMaterial)
      references DictSub (SubId) on delete restrict on update restrict;

alter table Products add constraint FK_BelongColor foreign key (SubIdBrand)
      references DictSub (SubId) on delete restrict on update restrict;

alter table Products add constraint FK_BelongInlay foreign key (SubIdInlay)
      references DictSub (SubId) on delete restrict on update restrict;

alter table Products add constraint FK_BelongMaterial foreign key (SubIdColor)
      references DictSub (SubId) on delete restrict on update restrict;

alter table Products add constraint FK_BelongMoral foreign key (SubIdTopLevel)
      references DictSub (SubId) on delete restrict on update restrict;

alter table Products add constraint FK_BelongTopLevel foreign key (SubIdMoral)
      references DictSub (SubId) on delete restrict on update restrict;

六、下载程序、帮助、视频

MySQL安装包

Learn MySQL database in 1 hour

MySQL视频教程

文档中没有您可以查帮助:

Learn MySQL database in 1 hour

图7:Learn MySQL database in 1 hour

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn