Basic knowledge of MySQL (detailed explanation of ten thousand words examples)

Article directory

1. What is MySQL?

First of all, MySQL is the most commonly used relational database operating language. Secondly, MySQL is a client server , which mainly realizes the interaction between the client and the server. Our usual consumption records, received vx messages, etc. are all through database-related products. To operate, and MySQL is one of the most commonly used languages ​​​​used to operate databases. Without further ado, let’s go directly to the topic!

2. MySQL common data types

1. String class

VARCHAR(n)	   字符/字符串。可变长度。最大长度 n
TEXT           长文本数据 
MEDIUMTEXT     中等长度文本数据 
BLOB           二进制形式的长文本数据                //varchar最为常用                      

2. Numerical type

BIT[ (M) ]    M指定位数,默认为1
TINYINT       1字节整形  
SMALLINT      2字节整形
INT           4字节整形
BIGINT        8字节整形
FLOAT(M, D)   4字节   单精度,M指定长度,D指定小数位数。会发生精度丢失
DOUBLE(M,D)     
DECIMAL(M,D)   M/D最大值+2  双精度,M指定长度,D表示小数点位数。精确数值
NUMERIC(M,D)   M/D最大值+2DECIMAL一样 

Note: You can specify unsigned type unsigned

3.Date type

DATETIME	8字节  范围从10009999年,不会进行时区的检索及转换。YYYY-MM-DD XX:XX:XX
TIMESTAMP    4字节  范围从19702038年,自动检索当前时区并进行转换。

3. Basic operations

1.MySQL statement common sense

  • Most MySQL statements need to be added; we use them without thinking; just
  • MySQL commands are not case-sensitive, do whatever you feel comfortable with
  • To improve readability, we should make good use of spaces to separate writing
  • MySQL usually uses - - to comment, you can also use #

2. Must know before learning - basic operations

Library level operations

SHOW DATABASES;                                    //显示所有数据库
CREATE DATABASE [IF NOT EXISTS] 库名;         //创建数据库(if语句:查找数据库,如果有,则不创建,可以省略)
USE  数据库名                                      //使用数据库
DROP DATABASE [IF EXISTS] 库名;                    //删除数据库
//这里比较简单,就不做实例演示啦~~~

Table level operations

show tables                                           //查看当前库里的表
desc  表名                                                 //查看表结构
drop  table [if exists]  表名;                            //删除表

3. Get to the point - add, delete, check and correct

Creating a table
Before adding, deleting, and checking, we must first have a table of our own. Here we take creating the student table as an example. The syntax is as follows:

create table + 表名 + (属性名称 属性类型,名称 类型,名称 类型...//创建

The example is as follows:
Insert image description here
Explanation: First select the library we want to operate. We are creating a table in the text library here, so we first enter the database and then create a student table with attributes id and name through the create statement~

Insert data - add

When we create a table, it is an empty table. At this time, we need to insert data to let the database play its role - storage and management. For insertion, the main insert statements used are as follows :

insert into 表名 values (值,值...);                                               //全表插入
insert into 表名 (列名,列名....) values (1,值2....//指定列进行插入
values+多个括号,括号之间要用,隔开                                               //一次插入多行

Examples are as follows:Insert image description here
Notice:When we insert a column in the table, the unassigned column will have a default value of NULL . This default value can be modified. We will introduce it later;

Query data - check

To say what is the most important thing about MySQL, query is well-deserved. Only users can search and see the data, and the data will be valuable. At the same time, query is also the most important and changeable syntax in MySQL, so let's do it together Look, the basic syntax for checking is as follows:

select * from 表名                                                //查询全表  通配符*表示所有的列
select 列名,列名  from 表名                                      //指定表中的列进行查询
//查询时可以对列进行运算,比如列+10,列1+列2....          //表达式查询(只在显示查询结果时生效一次,不会改变我们存储的值)
selectas 别名,列 as 别名  from 表名                          //查询时指定别名,可以但不推荐省略as 

We have just performed an insert operation on the student table. Next, we will perform an example query operation:
Insert image description here
Note: Such a query will definitely not meet our daily query needs, so we will derive many clauses to help our query operations, such as where Several clauses such as , group by, etc. help us with the query and modification below. We will introduce more query operations below. This article is long, so please read it patiently~

Modify data - change

To put it bluntly, the data we store is a kind of information. Most of this information changes at any time. At this time, we need to re-modify the outdated data. The syntax for modifying the data is as follows:

update 表名 set 列名=修改值,...   where/order by/limit等子句               //修改
//修改超出范围SQL会报错,且不生效
//修改小数点位数不够会发生截断(四舍五入)

Insert image description here
explainHere it means to modify name=xxx based on the condition of id=2, where means the conditional query clause , we just need to understand the modification syntax first, we will introduce it in detail later~

Delete data - delete

Some data will no longer be meaningful due to the passage of time, etc., and we need to delete it. The specific syntax is as follows:

delect  表名  from  子句                                            //删除操作某行或者整张表

Both deletion and modification operations are requiredWhere/order by/limit and other clausesTo assist in using it, we will provide detailed introduction below!

4. Look at the query again

1. Query common keywords

Remove duplicates——distinct

select distinct 列名 from 表名                                                    //去重查询,重复的行只保留第一个
//distinct 指定多个列时要求值都相同才视为重复

Example:Insert image description here

illustrateThis is based on our previous student table that added a new data with id=5 and name=wangwu. We use distinct to deduplicate the name column. Only one wangwu is displayed in the result table. It is worth noting that these operations are all in the results . The operations on the table are not modifications to the stored data~

Alias ​​- as

selectas 别名,列 as 别名  from 表名                          //查询时指定别名,可以但不推荐省略as 

Insert image description here

Fuzzy search——like

.like     模糊查找                                  //%算该位置处放0~n个字符模糊查找,_算该位置处一个字符 

Insert image description here

2. Logical operators and conditional operators

Operator operations are mainly used in where, having and other clauses (which will be introduced later). If the result is true, that is, TURE(1), it will appear in the result table, otherwise it will not appear !

Logical Operators

AND : Multiple conditions must be TRUE(1), the result is TRUE(1)
OR : Any one condition is TRUE(1), the result is TRUE(1)
NOT : The condition is TRUE(1), the result is FALSE( 0)

Note: The priority of and must be greater than or. When used at the same time, you need to use parentheses () to wrap the statement that is executed first to prevent incorrect use.

arithmetic operators

">, >=, <, <= " " Greater than, greater than or equal to, less than, less than or equal to
= : equal to, NULL is unsafe, for example, the result of NULL = NULL is NULL
<=> : equal to, NULL is safe, for example, NULL <= > The result of NULL is TRUE(1)
!=, <> : Not equal to
BETWEEN a0 AND a1 : Range matching, [a0, a1], if a0 <= value<= a1, return TRUE(1)
IN (option, … ) "If it is any one of the options, return TRUE(1) IS
NULL : It is NULL
IS NOT NULL : It is not NULL
LIKE : Fuzzy match. % represents any number (including 0) of any character; _ represents any character, which has been introduced previously.

3. Query sorting——order by

Sometimes we need to order the results of the query in order to meet our needs, so MySQL provides order by to sort the results.
The syntax is as follows:

-- ASC 为升序(从小到大)
-- DESC 为降序(从大到小)
-- 默认为 ASC
select */列名,列名... from 表名  order by 依据排序的列 [ASC/DESC];         //null在比较大小时默认是最小的~

We also create a student table containing grades for easy display. The example is as follows:
Insert image description here
illustrate: We first display our newly created student table, and then use the grade column** default asc sorting (ascending order) query. You can see that the results are increasing from top to bottom. The second result table specifies desc (descending order). **Query also meets our needs~

Details you shouldn’t miss—specifying multiple columns for sorting

Insert image description here

illustrate: In this result table, we choose id as the main column ( the column written in the front has a higher priority than the column written in the back, so id is the main column ), because after the ids are sorted, there are no identical id columns, so there is no need Sort the secondary columns, so in the result table, although we sort by the two columns id and grade, only the primary column id is in order, and the secondary column grade is still unordered.

4. Conditional query——where

Conditional query can be said to be the most critical query method. Whether it is querying, modifying or deleting, we have already seen where in the previous chapters. I believe everyone has some idea of ​​its role. Now that you know how to use it, let’s take a closer look at its usage~ First, the syntax is as follows:

select */列名,列名... from 表名  where 判断条件语句;   //这里的条件语句就是前边的运算符组成的语句,真则选择展示到结果表中
//这里要注意null与任何表达式计算结果都是null,因此用专用的<=>以及<>来判断是否值为空,才能使判断有意义

Examples are as follows:
Insert image description here
Here we give some examples of using other statements:

-- 查询语文成绩在 [80, 90] 分的同学及语文成绩
SELECT name, chinese FROM student WHERE chinese BETWEEN 80 AND 90;
-- 查询数学成绩是 58 或者 59 或者 98 或者 99 分的同学及数学成绩
SELECT name, math FROM student WHERE math IN (58, 59, 98, 99);
-- % 匹配任意0~n字符
SELECT name FROM student WHERE name LIKE 'z%';
-- 查询 qq_mail 已知的同学姓名
SELECT name, qq_mail FROM student WHERE qq_mail IS NOT NULL;

Due to space reasons, showing them one by one may make the article too long, so we will not show them with screenshots. The above sentences are all tested by bloggers and are absolutely correct!

where clause execution rules

Secondly, the judgment conditional statement of the where clause cannot use aliases . This is very unfriendly to many novices who have just entered the pit. The reason why it cannot be used is because the rules for executing the where clause are as follows:

  • First: each row of the table will be traversed
  • Secondly, bring each row traversed into the where clause for judgment.
  • Finally, bring the column whose result is true into select to perform queries or related operations on related columns.

5.Paging query——limit

Pagination query - simple and practical

In our daily life, it is impossible for one table to display all the information. We will divide it into pages and pages for query. To achieve this requirement, we use the limit statement. The syntax is as follows :

//默认从 0 开始,筛选 n 条结果
SELECT ... FROM 表名  LIMIT n;
// 从 s 开始,筛选 n 条结果
SELECT ... FROM 表名  LIMIT s, n;
// 从 s 开始,筛选 n 条结果,比第二种用法更明确,建议使用
SELECT ... FROM 表名  LIMIT n OFFSET s;

Examples are as follows:
Insert image description here

==Note: ==The first result table is a paging query starting from the 0 subscript by default, and the second result table is querying two results starting from the 1 subscript;

6. Use essential - continuous use of clauses

Sometimes a single query method cannot meet our various needs, so we treat where, limit and order by as clauses and use them with select. Of course, they are also occasionally used with update and deselect. Naturally, there can be many beside one master. sub, we stipulate the order of use as follows:

SELECT ... FROM 表名 [WHERE ...] [ORDER BY ...] [LIMIT ...];
UPDATE 表名 SET 列名=xx,列名=xx [WHERE ...] [ORDER BY ...] [LIMIT ...];
DELETE FROM  表名 [WHERE ...] [ORDER BY ...] [LIMIT ...]

Execution order

At present, we have the query related keyword execution order : from——where——select——distinct——as——order——limit;
This also shows that aliases cannot be used where, but ordery can be used.

5. Advanced necessary knowledge

1. List of common constraints

When we want to store data, we must abide by some rules from a management point of view. For example, the only thing a student has is a student ID. The grades can be unknown, but the student ID, name, etc. must be known. Therefore, the database has formulated constraints . Represents a set of "inspection rules" we have made for what can be written in the data in the database.

: Here we take sql5.7 as an example. Different versions may be slightly different . For example: sql5.7 does not support check constraints.

  • NOT NULL - the value is not empty.
  • UNIQUE - unique value.
  • DEFAULT - the default value.
  • PRIMARY KEY - primary key (not null + unique)
  • FOREIGN KEY - foreign key

The following examples all delete the student table first, and then re-create a constrained student table based on the constraint content! ! !

Non-null constraint——NOT NULL

NOT NULL: The selected column must not be empty when adding data. Usage examples are as follows:

//要求在填入学生信息时,id为必填项 其他项为选填项
CREATE TABLE student (
   id INT NOT NULL,
   sn INT,
   name VARCHAR(20),
   qq_mail VARCHAR(20)
);

Examples are as follows:
Insert image description here
illustrate: When inserting for the first time, the id column with a non-null constraint was not inserted, and an insertion error of 1364 was reported. The error message is also obvious as shown in the figure. It is caused by the id column. When the id was inserted for the second time, even if the qq_email column was not inserted, the id column was not inserted. No error will be reported, and the qq_email column is filled in with the default value null.

Unique constraint——UNIQUE

In our daily lives, some data are used to uniquely identify something, such as RMB codes, ID numbers, student numbers, etc. It is already a bit difficult to require that these data cannot be repeated when adding new data, so we use unique to constrain this Item addition operation, usage examples are as follows:

CREATE TABLE student (
 id INT NOT NULL,
 sn INT UNIQUE,
 name VARCHAR(20),
 qq_mail VARCHAR(20)
);

The usage is similar to not null, so we won’t go into too much detail.

Default value constraint - DEFAULT

When we are counting some data that cannot be obtained accurately, null sometimes cannot express the characteristics well. For example, when inserting the student table, if there is a list of class positions, we can set the default to be ordinary students if not filled in, etc., which facilitates our management. , and our MySQL has defaulted the unfilled default value to null, and also provides default to modify the default value.
Usage examples are as follows:

CREATE TABLE student (
 id INT NOT NULL,
 sn INT UNIQUE,
 name VARCHAR(20) DEFAULT 'unkown',
 qq_mail VARCHAR(20)
);

The example is as follows:
Insert image description here
Note: The default name is set here and is not filled in as unknown when adding data.

Primary key constraints——PRIMARY KEY

After learning this, have you tried using the first three constraints at the same time? Of course, the first two constraints and the third constraint cannot be used together logically. Only non-null constraints and unique constraints can be used at the same time. The next primary key constraint provided by SQL is actually a combined version of not null + unique. , used to ensure that a column (or a combination of two columns and multiple columns) has a unique identifier, which helps to find a specific record in the table more easily and quickly. Specific examples of usage are as follows:

CREATE TABLE student (
 id INT PRIMARY KEY,
 name VARCHAR(20)
);

The primary key must be unique and cannot be empty . One column can be used as the primary key, or multiple columns can be used as the primary key (composite primary key).

Let’s look at the following running results:
Insert image description here
explainHere you can see that a student table is first created, in which id is set as the primary key. When we specify a column to insert, id is the inserted data, and error code 1364 is reported, and error 1062 is reported when inserting the same column with the same id repeatedly , further indicating that it is not null Combined version with unique~

Auto-increasing primary key : Sometimes the amount of data is large, and the primary keys we use are arranged in increasing numbers. We wonder if there is a syntax that allows him to number the primary key himself, so the universal SQL provides an auto-increasing primary key:

// 从前一个序号开始+1作为下一个新增数据的主键内容添加,如果是第一个数据则从1开始
//我们在书写代码时,可以在添加主键时书写null,系统就自动实现主键的添加了
//如果不希望新插入的以自增方式添加,可以忽略自增主键,当普通主键手动添加~
id INT PRIMARY KEY auto_increment,

Insert image description here
Insert image description here

Foreign key constraints——FOREIGN KEY

When we create the student table, we will inevitably insert relevant content such as courses. However, we do not add this content out of thin air. We must ensure that the addition is meaningful. For example, if there is another course class, our student table is in the process of adding it. It is necessary to ensure that the added course column belongs to the course schedule. Of course, the demand is far more than that, so the foreign key constraint foreign key was born . The syntax is as follows:

foreign key (字段名) references 主表()

Here is an example :

//关于外键约束语法举例如下:
eg:
CREATE TABLE classes (
id INT PRIMARY KEY auto_increment,
name VARCHAR(20)
);
//插入数据,让classes表非空,不然其他表不能与空表建立外键约束
insert into classes values(null,'mysql');
//创建含有外键约束的student表
create table student (id int primary key,
 class_id int,
 foreign key (class_id) references classes(id)
 );

Insert image description here
explain: After we created the corresponding table, when we added data to the student table, the class_id inserted for the first time was not found in the id column in the classes table. The addition failed due to the foreign key constraint. For details, we can see the error message, Chapter When adding data to the student table for the second time, the class_id column of the student table is the same as the id column in the classes table, so the foreign key constraints are met and can be added!

Some notes on foreign key constraints:

  • The table that establishes foreign key constraints is called a child table . For example, if the student table is constrained by the class table, then the class table is the parent table of the student table, and vice versa.
  • The constraints between the parent table and the child table are mutual . When the child table is not empty, the parent table cannot be deleted. Friends, you can try it.
  • When establishing constraints on the child table, the parent table cannot be empty , otherwise an error will be reported.

2. Aggregation function query

Sometimes we need some specific methods to query, for example, there are 20 students in a class. We know the scores of these 20 students, how to quickly get the average score, highest score, etc. of the class. Aggregation query: During the query process, the table Certain operations are performed between rows and rows, relying on aggregate functions. MySQL provides a syntax called aggregate functions to assist us in querying. The main types of aggregate functions are as follows:

COUNT ([DISTINCT] expr) Returns the number of queried data
SUM ([DISTINCT] expr) Returns the sum of queried data, which is meaningless if it is not a number
AVG ([DISTINCT] expr) Returns the average of queried data, which is not Numbers are meaningless
MAX ([DISTINCT] expr) Returns the maximum value of the queried data. If it is not a number, it is meaningless.
MIN ([DISTINCT] expr) Returns the minimum value of the queried data. If it is not a number, it is meaningless.

Aggregation query usage examples

Create a table containing student math information:
Insert image description here
Insert the information:
Insert image description here
Query using aggregate functions in sequence:

Insert image description here
Precautions:

  • select count(*/列名) from 表名If you use column names, the corresponding column will not be counted in the quantity and sum.
  • The sum operation is similar to count. When sum is added, null l will be skipped. The other aggregate functions for numbers are also similar.
  • When using aggregate functions, please note that there cannot be a space between the function name and ()
  • The aggregate function aggregates the entire table by default . You can use the group by clause to perform partial table operations. group byThe clauses will be discussed next.

3. Reintroduction to query clauses

Group query——group by

The main function of grouping query is to group the same columns into one group. For example, to compare the average Chinese scores of boys and girls, we divide boys into one group and girls into one group. There are the following sayings about grouping query
:

Use the GROUP BY clause in SELECT to perform group queries on specified columns . Need to meet: When using the group clause, the column name followed by select must contain an aggregate function or a specified group by column, otherwise the query results are meaningless. We can think about why it is meaningless~

Grouping queries are similar to queries with conditions, and the syntax is relatively similar:

select ... from ... group by 列名  //将列中相同的分到一个组~~

The example is as follows:
We first create a new student table and have inserted data. The table here is as follows:
Insert image description here
We need to query the average scores of boys and girls in mathematics, as follows:
Insert image description here

Group by clause containing conditional query - HAVING, WHERE

having:

This is a clause specifically paired with group by, and its function is similar to where

We can perform conditional query before grouping and group the results obtained by the query; we can also group first and perform conditional filtering in the grouped results, or we can condition 1 - group - condition 2; above we use where and having , group by to achieve, our example is as follows:

//条件筛选——分组      
where 子句 group 子句
//分组————条件筛选
group 子句 having 子句  
//条件筛选1——分组——条件筛选2        
where 子句  group 子句  having 子句       

Let's continue adding data to the previous table:
Insert image description here
Query the average scores of boys and girls with scores greater than 60:
Insert image description here
Query the average scores of boys and girls with scores greater than 70:
Insert image description here
Query the average scores of boys and girls with scores greater than 60, and then check the average Average score greater than 80:
Insert image description here

6. The highlight of query - joint query of tables

In our real life, it is impossible for one table to solve all problems, and the joint use of several tables is often required. Therefore, a query method called joint query was born based on the Cartesian product , which can also be called a multi-table query . The Cartesian product Use the diagram below to understand:
Insert image description here
Note:关联查询可以对关联表使用别名。

//m*n行,m+n列;
select * from1,表2

1.Inner join

Inner join: The result set represented is the intersection of two tables , and its syntax is as follows:

//多表查询会有部分数据无效,利用 where子句来使表有意义,若两表列名重复,需要表名.列名的方式来访问 
//多表查询中:表1 join 表2 on 连接条件 join 表2 on 连接条件  等价于where子句
select 字段 from1 别名1 [inner] join2 别名2 on 连接条件 and 其他条件;
select 字段 from1 别名1,2 别名2 where 连接条件 and 其他条件

We first prepare the data, as follows:
Insert image description here
use where to query results:
Insert image description here
use join on to query results:
Insert image description here

2.Outer connection

Outer joins are divided into left outer joins and right outer joins. If a joint query is performed, if the table on the left is completely displayed, we say it is a left outer join; if the table on the right is completely displayed, we say it is a right outer join. The main syntax is as follows:

// 左外连接,表1完全显示
select 字段名  from 表名1 left join 表名2 on 连接条件;
// 右外连接,表2完全显示
select 字段 from 表名1 right join 表名2 on 连接条件;

Query grades and classmates' personal information. If the student has no grades,
Insert image description here
multiple tables need to be displayed for joint query: Take 3 tables as an example, first consider the temporary table obtained in the left middle, and perform an outer join between the temporary table and the right

3.Self-query

Self-query: do a Cartesian product with yourself; main purpose: Our operations are all performed on columns, and changing rows into columns is beneficial to our query.
Take the above table as an example: query students whose math scores are lower than mysql scores:
Insert image description here
illustrate:Because of the nature of the Cartesian product, we need to use
distinct
for deduplication.

4. Subquery

To put it bluntly, a subquery is a matryoshka query, which refers to a select statement embedded in other SQL statements, also called a nested query.

  • Single row subquery: eg:select 语句 查询子句[列名 = (select语句)] //注意可读性,善用()
  • Multi-row subquery:where 列 in (select语句)

For example, we query the mysql scores of students with math=58 without knowing their names:
Insert image description here

5. Combined queries

**Merge query:** Merge the results of multiple queries into one table, similar to or but with a wide scope. Note: union和union allWhen used, the fields in the result sets of the previous and subsequent queries need to be consistent.

  • nuion: Automatically remove duplicate columns
  • union all: will not automatically remove duplicates
  • Union queries multiple tables and automatically removes duplication, or can only query one table.

For example, find the names of students with id<2 or math>60 from the above student table and grade table :
Insert image description here

Use the results table without deduplication:
Insert image description here

7. Some matters that need to be explained

1. How to enter Chinese characters in SQL

The default character set of the database is "Latin", which cannot represent Chinese characters. When creating the library, use the database creation statement + charset utf8 to match.

2.SQL security

Simply put, there are no safe operations in SQL. You need to be careful when using it at work. It may also crash due to operations such as deletion while studying~

3.What is int(11)

int(11)                     //表示int型,在查询时最多显示11个字符,与存储无关

4. Overview of SQL execution sequence - key points

This is more important. Only by knowing the execution order can you use SQL correctly. The execution order is roughly as follows:
from ——on ——join ——where ——group by (start using the alias in select, and you can use it in subsequent statements. )—— Aggregation function——having——select——distinct——order by——limit

8. The last and the last

Thank you very much for reading this. We have mastered so much about the use of SQL and this is basically over. But you must still be curious about how to use mysql with Java, c++ and other languages ​​on the Internet. Regarding these, the blogger will update JDBC programming in the future . It will also expand mysql's index and transaction related and use multi-threading to complete some underlying operations of mysql. You may wish to follow the blogger, and we look forward to the follow-up exciting content of mysql~

Guess you like

Origin blog.csdn.net/m0_65038072/article/details/130226306