[The road to database clearance] MySQL whole route learning knowledge points combing (middle)

foreword

This article is the second article in the series of MYSQL zero-based Xiaobai learning , click here to read the previous article

At the end of the article, a copy of "Core Principles of Distributed Middleware and Best Practices of RocketMQ" (click on the catalog below) will be sent by free mail. For every +1000 views of this article, an extra person will be selected
insert image description here

6. Detailed explanation of practical cases

Requirement : Design a student table containing the following information, please pay attention to the rationality of data type and length.

  1. serial number
  2. Name, the longest name shall not exceed 10 Chinese characters
  3. Gender, because there are only two possible values, so at most one Chinese character
  4. birthday, the value is year month day
  5. Grades, keep two digits after the decimal point
  6. Address, the maximum length does not exceed 64
  7. Student status (in numbers, on track, on leave, graduated...)

Before completing such a case, first create a student database, create a new table in the database, and pay attention to the syntax format, data type, and length of the table when creating the table.

Run the command prompt cmd as an administrator, start the Mysql service, and log in to MySQL:

insert image description here

Create a student information database:

create database if not exists student;

insert image description here

Use studentthe database:

use student;

insert image description here

Create a data table:

create table stu(
		id int ,-- 编号
		name varchar(10),-- 姓名
		gender char(1),-- 性别
		birthday date,-- 生日
		score double(5,2) ,-- 分数
		addr varchar(50),-- 地址
		status tinyint-- 状态
);

insert image description here


Now, we have learned to write SQL to operate the database, but when we write SQL on the command line, we often have problems such as poor experience and low efficiency. Now we have to learn 在MySQL的图形化客户端Navicat中执行SQL语句.

insert image description here

Navicat provides an intuitive and powerful graphical interface for database management, development and maintenance, which greatly improves work efficiency. It is recommended to use this development tool in learning.接下来,在Navicat中新建数据库,新建查询,我们就可以编写SQL并且执行SQL语句了。

7. DML- add, delete, modify data

7.1 Add data

Add data to the specified column:

insert into 表名(列名1,列名2...) values(1,2...);

Add data to all columns:

insert into 表名 values(1,2...);

Add data in batches:

insert into 表名(列名1,列名2...) values(1,2...),(1,2...)(1,2...)...;

Add data in batches (omit the field name):

insert into 表名 values(1,2...),(1,2...)(1,2...)...;

It is not recommended to omit the field name when adding data during the development process, which reduces the readability of the code and reduces the efficiency. For example:

The way to query all the data in the table is:

select * from 表名;

Will be used later.

Requirement: Add a piece of data to the table below tb_user.

insert image description here

insert into tb_user(id,name) values(2,'李四');

Added successfully:

insert image description here


7.2 Modify data

Modify table data:

update 表名 set 列名1=1,列名2=2...[where 条件];

When modifying data, it is not necessary to use the where condition. At this time, the operation is to modify the entire column of data, which is very dangerous.

Requirement: Change tb_userthe password of Zhang San in the table below to abc23

insert image description here

update tb_user set passwor d ='abc123' where name='张三';

Successfully modified:

insert image description here


7.3 Delete data

Delete table data:

delete from 表名 [where 条件];

When deleting a piece of data, if the where condition is not used, the data in the entire table will be deleted.

Requirement: Delete the Li Si record in the tb_user table.

delete from tb_user where name='李四';

Successful operation:

insert image description here

8. DQL- data query operation

查询是数据操作至关重要的一部分,For example, if you want to find out all the products whose prices are within the specified range among all the products, if you want to display the data in the database to the user on the client, you usually have to perform a query operation.

In actual development, we need to decide how to query according to different needs and consider the efficiency of the query. Before learning query, you can take a look at the complete syntax of the query:

SELECT
	字段列表
FROM
	表名列表
WHERE
	条件列表
GROUP BY
	分组字段
HAVING
	分组后条件
ORDER BY
	排序字段
LIMIT
	分页限定

According to the keywords in the complete syntax of the query, we learn separately基础查询,条件查询,排序查询,分组查询和分页查询。

The following exercises use the following case study single-table query:

-- 删除stu表
drop table if exists stu;
-- 创建stu表
CREATE TABLE stu (
id int, -- 编号
name varchar(10), -- 姓名
age int, -- 年龄
gender varchar(5), -- 性别
math double(5,2), -- 数学成绩
english double(5,2) -- 英语成绩

);
-- 添加数据
INSERT INTO stu(id,name,age,gender,math,english)
VALUES
(1,'小张',23,'男',66,78),
(2,'小李',20,'女',98,87),
(3,'小陈',55,'男',56,77),
(4,'小樊',20,'女',76,65),
(5,'小马',20,'男',86,NULL),
(6,'小赵',57,'男',99,99);

Select SQL in Navicat and execute:

insert image description here

8.1 Basic query

1. Basic query syntax

Query multiple fields:

select 字段列表 from 表名;

Query all fields:

select * from 表名;

Remove duplicate records:

select distinct 字段列表 from 表名;

Alias ​​operation:

select 字段名 别名 from 表名;

2. Basic query practice

Use the student table for basic query exercises:

Exercises for querying multiple fields:

select name,math from stu;

insert image description here

Alias ​​operation practice:

select name,english 英语成绩 from stu;

insert image description here

8.2 Condition query

1. Conditional query syntax

General syntax:

select 字段列表 from 表名 where 条件列表;

Conditional queries are generally performed with operators, and the following are some common operators:

operator Functional description
> < = ! greater than less than equal to not equal to
between…and… within this range
in(…) choose one
is null / is not null is null / is not null
and 或 && and
or 或 || or

2. Condition query practice

Use the student table for conditional query exercises:

Query the information of students whose age is older than 20:

select * from stu where age>20;

insert image description hereQuery the information of students whose age is equal to 18, or whose age is equal to 20, or whose age is equal to 21:

select * from stu where age in(18,20,21);

insert image description hereFuzzy queries use the like keyword, and wildcards can be used for placeholders:

  • _ : represents a single arbitrary character
  • % : represents any number of characters

Query information about students whose names contain Zhang:

select * from stu where name like '%张%';

insert image description here

8.3 Sorting queries

1. Sort query syntax

select 字段列表 from 表名 order by 排序字段名1 [排序方式]...;

Note : There are two sorting methods: ascending ASC and descending DESC, and the default is ascending ASC.

2. Sorting query practice

Use the student table for sorting query exercises:

Query student information, sorted in descending order of math scores:

select * from stu order by math DESC;

8.4 Aggregate functions

1. Aggregate Function Syntax

What is an aggregate function? When performing query operations, it is often necessary to perform operations on an entire column. For example, to calculate the average value of an entire column of grade data, we need to use aggregate functions. The following are common aggregate functions:

Function name Function
count(column name) Statistical quantity (generally choose a column that is not null)
max(column name) maximum value
min(column name) minimum value
sum(column name) to sum
avg(column name) average value

General syntax:

select 聚合函数 from 表名;

Note: NULL values ​​do not participate in aggregation function operations.

2. Aggregate function practice

An exercise in aggregate functions using the student table:

Count how many students there are in this table:

select count(id) from stu;

insert image description here

Above we use a certain field to perform calculations. The problem we may face is that a certain value may be NULL, so we generally use *to perform calculations, because it is impossible for all fields in a row to be NULL.

select count(*) from stu;

Query the average score of math scores:

select avg(math) from stu;

insert image description here

8.5 Group query

1. Group query syntax

select 字段列表 from 表名 [where 分组前的条件限定] group by 分组字段名 [having 分组后的条件过滤]

Note: After grouping, the fields to be queried are aggregation functions and grouping fields, and it is meaningless to query other fields.

2. Group query practice

Use the student table for group query exercises:

Query the average math scores of male and female students, as well as their respective numbers. Requirements: those with scores below 70 do not participate in the group:

select gender, avg(math),count(*) from stu where math > 70 group by gender;

insert image description here

Query the average math scores of male and female students, as well as their respective numbers. Requirements: those whose scores are lower than 70 do not participate in the grouping, and those whose numbers are greater than 2 after grouping:

select gender, avg(math),count(*) from stu where math > 70 group by gender having count(*) > 2;

insert image description here

Note: where 和 havingThe execution timing is different: where is limited before grouping, if the where condition is not met, it will not participate in grouping, and having is to filter the results after grouping. Therefore, where cannot judge the aggregate function, but having can.

8.6 Pagination query

1. Paging query syntax

In our impression, when a web page displays a large amount of data, it often does not display all the data at once, but in the form of paged display. In fact, it is the operation of querying the data in pages, that is, only one page of data is queried at a time. displayed on the page.

select 字段列表 from 表名 limit 查询起始索引,查询条目数;

In limitthe keyword , the query starting index parameter starts from 0.

2. Paging query practice

Use the student table for pagination query practice:

Start query from 0, query 3 pieces of data:

select * from stu limit 0,3;

insert image description here起始索引 = (当前页码 - 1) * 每页显示的条数

在SQL标准中,一共规定了6种不同的约束,Including non-null constraints, unique constraints, and check constraints, etc., but check constraints are not supported in MySQL, so this article first explains and exercises the remaining 5 constraints.

9. The concept of constraints

约束是作用于表中列上的规则,用于限制加入表的数据。For example, the column used as the primary key must be non-empty and unique, otherwise the data will not be able to be distinguished. The existence of constraints guarantees the correctness, validity and integrity of the data in the database. So constraints are very important in database design.

10. Classification of Constraints

As mentioned earlier, the SQL standard divides constraints into 6 categories, namely non-null constraints, unique constraints, primary key constraints, check constraints, default constraints and foreign key constraints. When adding constraints, we only need to add keywords in SQL to restrict the data in the table.

constraint type Function
NOT NULL constraint Ensure that all data in the column cannot have null values
Unique constraint UNIQUE Guarantees that all data in a column is distinct
Primary key constraint PRIMARY KEY The primary key is the unique identifier of a row of data, which requires non-null and unique
check constraint CHECK Guarantees that the values ​​in a column satisfy a certain condition
default constraint DEFAULT When saving data, if no value is specified, the default value will be used
Foreign key constraint FOREIGN KEY Foreign keys are used to establish links between data in two tables to ensure data consistency and integrity

11. Not-null constraints

Purpose: To ensure that all data in the column cannot have null values

Add constraints:

CREATE TABLE 表名(
	列名 数据类型 NOT NULL,);

Add a non-null constraint after the table is built:

ALTER TABLE 表名 MODIFY 字段名 数据类型 NOT NULL;

Remove constraints:

ALTER TABLE 表名 MODIFY 字段名 数据类型;

12. Unique constraints

Purpose: To ensure that all data in the column are different

Add constraints:

CREATE TABLE 表名(
	列名 数据类型 UNIQUE [AUTO_INCREMENT],
	-- AUTO_INCREMENT: 当不指定值时自动增长);

CREATE TABLE 表名(
	列名 数据类型,[CONSTRAINT] [约束名称] UNIQUE(列名)
);

After the table is built, add unique constraints:

ALTER TABLE 表名 MODIFY 字段名 数据类型 UNIQUE;

Remove constraints:

ALTER TABLE 表名 DROP INDEX 字段名;

【Free book】

Distributed Middleware Core Principles and RocketMQ Best Practices

[! way of participation!

Like+Favorite+Comment on this article " Life is short, I love MySQL "
Deadline: 2023-04-15 9:00 AM

Note: The lucky draw method is <program random draw>, and the winners will be announced on my homepage as scheduled, with free shipping.


【Introduction↓】

This book starts from the basic concepts of distributed systems, gradually deepens the advanced practice of middleware in distributed systems, and finally explains with a large-scale project case, focusing on the process of using Spring Cloud framework to integrate various distributed components. It allows readers not only to systematically learn the relevant knowledge of distributed middleware, but also to have a deeper understanding of business logic analysis ideas and practical application development.

The book is divided into 12 chapters, the first three chapters are the preparation stage for learning distributed system architecture. The opening part of Chapter 1 explains how distributed systems emerge during the evolution process; Chapter 2 Spring explains how to build the currently popular Spring Boot and Spring Cloud frameworks; Chapter 3 Containers explains the most popular Docker containers at present Technology and Kubernetes container orchestration tools; Chapters 4~8 explain in depth the relevant knowledge of message middleware RocketMQ, where theory and practice coexist; Chapter 9 will go deep into the bottom layer of RocketMQ, explore the fun of reading source code, and learn to read source code while mastering RocketMQ Methods; Chapters 10 and 11 explain the issues that must be considered in distributed systems: distributed transactions and distributed locks; Chapter 12 takes an e-commerce system business as an example, allowing readers to experience the process of a project from scratch , and apply what you have learned.

The content of this book is from shallow to deep, with a clear structure, rich examples, easy to understand, and strong practicability. It is suitable for those who need to learn all-round technologies related to distributed middleware, and it is also suitable for training schools as training materials. Teaching reference books for relevant majors in colleges and universities.
Jingdong self-operated purchase link: "Core Principles of Distributed Middleware and Best Practices of RocketMQ"

insert image description here

Guess you like

Origin blog.csdn.net/m0_63947499/article/details/129844215