Advanced SQL statement of MySQL database

Table of contents

1. MySQL statement preface

1.1 Sort by keyword 

 1.2 Environment preparation

 1.3 Single field sorting

1.3.1 Ascending order

  1.3.2 Descending order

  1.3.3 order by can also be combined with where for conditional filtering

​Edit 1.4 Multi-field sorting

 1.4.1 Query student information in ascending order of interest id first, for the same score, id in descending order

 1.4.2 Query student information in ascending order of interest id first, for the same score, id is arranged in ascending order

  1.5 Interval judgment and query for non-duplicate records

  1.5.1 Interval judgment AND (and)/OR (or)

  1.6 Nested/multiple conditions

  1.7 Query without duplicate records

 2. Group the results

 2.1. Count the number of ids with the same interest and group them according to the same hobby

  2.2. According to the group with the same hobby, calculate the number of students with the same score

2.3 Screen the groups whose scores are greater than or equal to 80, and calculate the number of students

3. Restrict result entries

 3.1 Query all information and display the first 4 rows of records

 3.2 Starting from line 3, display 4 lines later

 3.3 Combining the order by statement, display the id size of the first 3 rows in ascending order

 4. Set an alias (alias->as)

4.1 Column aliases

 4.2 Table alias settings

  4.3 Check the nannan table and display it by address

 4.4 AS can also be used as the operator of the connection statement: insert all the query records of the huanjing table into the test1 table

 4.5 Add where statement judgment

 5. Wildcards

 5.1 Find records that start with x

 5.2 Find records ending with n

  5.3 Find records that only contain a

 5.4. Find records containing x and n at the same time

  5.5 Find the record between a and g

 5.6 Find records with 3 characters after xiao

  6. Sub query

 6.1 Query of the same table

  6.2 Different Table/Multiple Table Query

 6.2.1 NOT Negation

 6.3 Use of different statements

6.3.1 Query records with scores greater than 80

 6.3.2.inset (add)

 6.3.3.update (modify)

 6.3.4.delete (delete)

  6.3.5.exists

 6.3.6 as aliases

  Seven. Mysql view

 7.1. Overview of views

   7.2. View functionality

   7.3. The difference between views and tables

 7.4. Relationship between views and tables

7.5. Creating Views

 7.6 Check the structure of view and source table

  7.7 Modify view data (source table data also changes)

  7.8 Modify source table data (view data also changes)

  Eight. NULL value

 8.1 Overview of NULL

8.2 The difference between empty value (NULL) and no value (' ')

 8.3 View the source table and insert a record

 8.4 Check whether null will be added to the statistics

9. Connection query 

 9.1 Query Overview

 9.2 Inner joins

 9.3 Left join

9.4 Right join

1. MySQL statement preface

  • In addition to the basic query, the query to the MySQL database sometimes needs to process the result set of the query. For example, only take 10 pieces of data, sort or group query results, and so on.

1.1 Sort by keyword 

  • PS: It is somewhat similar to Windows Task Manager
  • ​Use the select statement to query the required data from the mysql database. If the query results are sorted, you can use the order by statement to complete the sorting, and finally return the sorted results to the customer. The sorting of this statement can be not only for a certain field, but also for multiple fields.
1.​select 字段 from 表名 order by 字段 ASC|DESC​
 
​2.ASC|DESC​
 
​3.ASC 是按照升序进行排名的,是默认的排序方式,即ASC可以省略​
 
4.​DESC 是按照降序的方式进行排序的​
 
5.​order by 也可以通过 where 子句对查询结果进行进一步的过滤​
 
​可进行多字段的排序

 1.2 Environment preparation

 

 1.3 Single field sorting

1.3.1 Ascending order

select * from huanjing order by score; (asc默认省略)

  1.3.2 Descending order

select * from huanjing order by score desc;

  1.3.3 order by can also be combined with where for conditional filtering

select * from huanjing where address=’杭州’ order by score desc;

 1.4 Multi-field sorting

The ORDER BY statement can also use multiple fields to sort. When there are multiple records with the same first field to be sorted, these multiple records will be sorted according to the second field. ORDER BY is followed by multiple Fields are separated by English commas, and the priority is determined in order, but the second field is meaningful only when the first parameter after order by has the same value.

 1.4.1 Query student information in ascending order of interest id first, for the same score, id in descending order

select * from huanjing order by hobbid,id desc;

 1.4.2 Query student information in ascending order of interest id first, for the same score, id is arranged in ascending order

select * from huanjing order by hobbid,id;

  1.5 Interval judgment and query for non-duplicate records

  1.5.1 Interval judgment AND (and)/OR (or)

select * from huanjinggaojie where hobby>3 and id<5;
 
select * from huanjing where hobby>3 or id<5;

  1.6 Nested/multiple conditions

举个例子(括号里的条件可以随意加):
select * from huanjing where hobby>2 or (hobby>3 and id<5);
 
又或者加入上面的降升序
select * from huanjing where hobby>2 and id<6 oredr by hobby desc;

  1.7 Query without duplicate records

 select distinct 字段 from 表名;
 
注意:
 distinct 必须放在最开头
 
 distinct 只能使用需要去重的字段进行操作
 
 distinct 去重多个字段时,含义是:几个字段同时重复时才能被过滤,会默认按左边第一个字段为依据。

 2. Group the results

The results obtained through SQL query can also be grouped, and the GROUP BY statement is used to implement
GROUP BY is usually used in conjunction with aggregate functions.
Commonly used aggregate functions include: count (COUNT), sum (SUM), and average Amount (AVG), maximum value (MAX), minimum value (MIN), when grouping by GROUP BY, the results can be grouped by one or more fields.

select 字段,聚合函数 from 表名 (where 字段名(匹配) 数值) group by 字段名;

 2.1. Count the number of ids with the same interest and group them according to the same hobby

select count(id),hobby from huanjing group by hobby;

  2.2. According to the group with the same hobby, calculate the number of students with the same score

select count(name),score from huanjing group by score;

2.3 Screen the groups whose scores are greater than or equal to 80, and calculate the number of students

select count(name),score from huanjing where score>=80 group by score;

3. Restrict result entries

  • limit limit output result records
  • When querying using the MySQL SELECT statement, the result set returns all matching records (rows). Sometimes only the first row or the first few rows need to be returned, and the LIMIT clause is needed at this time
1.select 字段 from 表名 limit [offset,] number
 
2.limit 的第一个参数是位置偏移量(可选参数),是设置 mysql 从哪一行开始
 
3.如果不设定第一个参数,将会从表中的第一条记录开始显示。
 
4.第一条偏移量是0,第二条为1
 
5.offset 为索引下标
 
6.number 为索引下标后的几位

 3.1 Query all information and display the first 4 rows of records

select * from huanjing limit 4;

 3.2 Starting from line 3, display 4 lines later

select * from huanjing limit 3,4;

 3.3 Combining the order by statement, display the id size of the first 3 rows in ascending order

 

 4. Set an alias (alias->as)

  • When querying in mysql, when the name of the table is relatively long or some fields in the table are relatively long, in order to facilitate writing or use the same table multiple times, you can set an alias for the field column or table to facilitate operation and enhance readability.
  • When querying complex tables, aliases can shorten the length of query statements
  • When multiple tables are connected to query (easy to understand, shorten sql statement)
对于列的别名  select 字段 as 字段别名 表名
 
对于表的别名 select 别名.字段 from 表名 as 别名
 
例如:
对于列的别名:SELECT column_name AS alias_name FROM table_name;
 
对于表的别名:SELECT column_name(s) FROM table_name AS alias_name;

4.1 Column aliases

 4.2 Table alias settings

  4.3 Check the nannan table and display it by address

select count(*) as address from nannan;

 4.4 AS can also be used as the operator of the connection statement: insert all the query records of the huanjing table into the test1 table

此处 AS 起到的作用:
1、创建了一个新表 nannan1 并定义表结构,插入表数据(与 info 表相同)
2、但是 "约束" 没有被完全 "复制" 过来,但是如果原表设置了主键,那么附表的 default 字段会默认设置一个 0
相似:克隆、复制表结构

 

 4.5 Add where statement judgment

在为表设置别名时,要保证别名不能与数据库中的其他表的名称冲突

列的别名是在结果中有显示的,而表的别名在结果中没有显示,只在执行查询时使用
create table test2 as select * from huanjing where score >=80;

 5. Wildcards

  • Wildcards are mainly used to replace some characters in a string, and query related results by matching some characters.
  • Usually wildcards are  used together with  LIKE , and cooperate with the WHERE clause to complete the query task. Usually there are two wildcards, namely:
% The percent sign means zero, one or more characters
_ Underscores represent single characters

 5.1 Find records that start with x

 5.2 Find records ending with n

  5.3 Find records that only contain a

 5.4. Find records containing x and n at the same time

  5.5 Find the record between a and g

 5.6 Find records with 3 characters after xiao

  6. Sub query

  • A subquery is also called an inner query or a nested query. It means that a query statement is nested inside another query statement. The subquery statement is executed before the main query statement, and the result is returned to the main query statement as an outer condition. Query for the next step of query filtering
  • The substatement can be the same as the table queried by the main statement, or it can be a different table

 6.1 Query of the same table

<表达式>[NOT] IN<子查询>

  6.2 Different Table/Multiple Table Query

 6.2.1 NOT Negation

 6.3 Use of different statements

Subqueries can be used not only in SELECT statements, but also in INERT, UPDATE, and DELETE. When nesting, a new subquery can be nested inside the subquery, that is to say, it can be nested in multiple layers.

Returns TRUE if the expression is equal to a value in the result set returned by the subquery, otherwise returns FALSE. If the NOT keyword is enabled, the return value is reversed. It should be noted that a subquery can only return one column of data. If the requirements are complex and one column cannot solve the problem, multi-level nesting can be used to deal with it. In most cases, subqueries are used with the SELECT statement.

IN 用于判断某个值是否在给定的结果集中,通常结合子查询来使用
<表达式> [NOT] IN <子查询>

6.3.1 Query records with scores greater than 80

select name,score from huanjing where id in (select id from huanjing where score > 80);

 6.3.2.inset (add)

  • The subquery can also be used in the insert statement, and the result set of the subquery can be inserted into other tables through the insert statement
insert into test2 select * from huanjing where id in (select id from huanjing);

 6.3.3.update (modify)

  • The update statement can also use a subquery. The subquery in the update can be a single column or multiple columns when the set updates the content.

 6.3.4.delete (delete)

  6.3.5.exists

  • The exists keyword is mainly used to determine whether the result set of the subquery is empty in the subquery. If it is not empty, it returns true, otherwise it returns false
  • When using exists, when the subquery has a result, the main query operation is executed regardless of the content of the subquery; when the subquery has no result, the main query operation is not executed.

 6.3.6 as aliases

  • When querying the result set as a table, you need to use an alias

  Seven. Mysql view

 7.1. Overview of views

The difference between the view table is that the table actually stores data, while the view is a structure built on the table, and it does not actually store the data itself.

Temporary tables disappear automatically after the user logs out or the connection to the database is disconnected, but the view does not disappear.

A view does not contain data, only its definition is stored, and its use generally simplifies complex queries. For example, if you want to perform join queries on several tables, and also perform statistical sorting operations, it will be very troublesome to write SQL statements. Using a view to join several tables, and then performing query operations on this view is the same as performing operations on a table. Queries are the same, very convenient.

   7.2. View functionality

  • Simplified query result sets, flexible query, can present different result sets for different users, relatively higher security.
  • In essence, a view is a select (result set presentation).
  • Views are suitable for multi-table connection browsing! It is not suitable for addition, deletion and modification, and stored procedures are suitable for frequently used SQL statements, which can improve execution efficiency.

   7.3. The difference between views and tables

        Views are compiled SQL statements. while the table is not

        Views do not have actual physical records. And the table has. show table status\G

        Tables only use physical space and views do not occupy physical space. Views are only the existence of logical concepts. Tables can be modified in time, but views can only be modified by created statements

        A view is a way to view a data table. It can query the data composed of certain fields in the data table. It is just a collection of some SQL statements. From a security point of view, the view does not allow users to access the data table, so they do not know the table structure.
A table belongs to a table in the global schema and is a real table; a view belongs to a table in a local schema and is a virtual table.
The establishment and deletion of a view only affects the view itself, not the corresponding basic table. (But updating the view data will affect the basic table)

 7.4. Relationship between views and tables

        A view (view) is a table built on top of the basic table. Its structure (that is, the defined columns) and content (that is, all data rows) come from the basic table, and it exists according to the existence of the basic table. A view can correspond to one basic table or multiple basic tables. Views are abstractions of base tables and new relationships established in a logical sense.

7.5. Creating Views

create view 视图表名 as select * from 表名 where 查找条件;

 7.6 Check the structure of view and source table

  7.7 Modify view data (source table data also changes)

  7.8 Modify source table data (view data also changes)

  Eight. NULL value

 8.1 Overview of NULL

During the use of SQL statements, the characters NULL are often encountered. Usually use NULL to represent missing values, that is, the field has no value in the table. If you restrict certain fields from being empty when creating a table, you can use the NOT NULL keyword, and if you don't use it, it can be empty by default. When inserting or updating records into the table, if the field does not have NOT NULL and has no value, the field of the new record will be saved as NULL at this time. It should be noted that the NULL value is different from the number 0 or blank (spaces) field, and the field with the value of NULL has no value. In the SQL statement, use IS NULL to judge whether a field in the table is a NULL value, on the contrary, use IS NOT NULL to judge whether it is a NULL value

8.2 The difference between empty value (NULL) and no value (' ')

The length of no value is 0, which does not take up space; while the length of NULL value is NULL, which takes up space.
ISNULL or IS NOT NULL is used to judge whether the field is NULL or not NULL, and cannot find out whether it has no value.
Use ='' or <>'' to handle the judgment of no value. <> represents not equal to.
When using count() to specify the number of rows in the field statistics, if a NULL value is encountered, it will be automatically ignored, and if no value is encountered, it will be added to the record for calculation.
NULL takes up memory space, while empty value does not take up memory space 

 8.3 View the source table and insert a record

desc huanjing;
alter table huanjing add column addr varchar(50);

 8.4 Check whether null will be added to the statistics

9. Connection query 

 9.1 Query Overview

  • MysgL's join query usually combines the records and rows from two or more tables, and splices data based on the common fields between these tables. First, determine a main table as the result set, and then selectively connect the rows of other tables to the selected main table result set. Join queries that use more include: inner join, left join and right join

 9.2 Inner joins

        An inner join in MysQL is a combination of data records in two or more tables that meet certain conditions at the same time. Usually, the keyword INNERJOIN is used in the FROM clause to join multiple tables, and the ON clause is used to set the connection condition. The inner join is the default table connection of the system, so the INNER keyword can be omitted after the FROM clause, and only the keyword is used. Join. When there are multiple tables at the same time, INNER JOIN can also be used continuously to realize the internal connection of multiple tables, but for better performance, it is recommended not to exceed three tables

Inner query: output the record rows of the same field specified by the two tables through inner join

Inner join query: In the interview, it is straightforward to say that you can use inner join

SELECT * FROM huanjing A INNER JOIN huanjing B on A.name = B.name;

 9.3 Left join

Left join can also be called left outer join, use LEFT JOIN or LEFT OUTER JOIN keywords in the FROM clause to express. The left join takes the left table as the base table, receives all the rows of the left table, and uses these rows to match the records in the right reference table, that is, matches all the rows in the left table and the qualified rows in the right table.

Match the contents of the two tables, and output all the contents of the left table and the common data content on the right according to the order of the SQL query (left->right)

In the left join, all the records in the left table will be displayed, while the right table will only display the records that meet the search conditions, and the places where the records in the right table are insufficient are NULL.

SELECT * FROM huanjing A left join huanjing B on A.name = B.name;

9.4 Right join

Right joins are also called right outer joins, and are represented by the RIGHTJoIN or RIGHT OUTER JOIN keywords in the FROM clause. A right join is just the opposite of a left join. It uses the right table as the base table to receive all the rows in the right table and use these records to match the rows in the left table.

In the right join query result set, in addition to the rows that meet the matching rules, there are also rows that exist in the right table but do not match in the left table, and these records are supplemented with NULL in the left table

SELECT * FROM huanjing A right join huanjing B on A.name = B.name;

Guess you like

Origin blog.csdn.net/m0_57554344/article/details/131788206