当前位置:网站首页>Sorting and paging
Sorting and paging
2022-06-10 15:43:00 【CaraYQ】
Catalog
Sorting data
One 、 Sort rule : Use ORDER BY Sort the queried data .
- Ascending :ASC( Default )
- Descending :DESC
Two 、ORDER BY Clause in SELECT End of statement .
# practice : according to salary Display employee information from high to low
SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary DESC;
# practice : according to salary Display employee information from low to high
SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary ASC;
SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary; # If in ORDER BY If there is no explicit naming sort after , Sort in ascending order by default .
#2. We can use column aliases , Sort
SELECT employee_id,salary,salary * 12 annual_sal
FROM employees
ORDER BY annual_sal;
# Column aliases can only be used in ORDER BY Use in , Can't be in WHERE Use in .
# The following operation reports an error !
SELECT employee_id,salary,salary * 12 annual_sal
FROM employees
WHERE annual_sal > 81600;
#3. Emphasis format :WHERE Need to declare in FROM after ,ORDER BY Before .
# Sort fields can be different from query fields
# The query statement does not query from top to bottom , Instead, find the table first (FROM employees),
# Then filter the table (WHERE department_id IN (50,60,70)), Then the query (SELECT employee_id,salary),
# Last sort (ORDER BY department_id DESC;)
SELECT employee_id,salary
FROM employees
WHERE department_id IN (50,60,70)
ORDER BY department_id DESC;
#4. Secondary sorting
# practice : Show employee information , according to department_id Descending order of , in the light of department_id The same employees , according to salary In ascending order
SELECT employee_id,salary,department_id
FROM employees
ORDER BY department_id DESC,salary ASC;
Pagination
One 、mysql Use limit Realize pagination display of data
Two 、 Format :LIMIT [ Position offset ,] Row number . first “ Position offset ” Parameters indicate MySQL Which line to start with , Is an optional parameter , If you don't specify “ Position offset ”, It will start with the first record in the table ( The position offset of the first record is 0, The position offset of the second record is 1, And so on ); The second parameter “ Row number ” Indicates the number of records returned .
# demand 1: Each page shows 20 Bar record , The... Is displayed 1 page
SELECT employee_id,last_name
FROM employees
LIMIT 0,20;
# demand 2: Each page shows 20 Bar record , The... Is displayed 2 page
SELECT employee_id,last_name
FROM employees
LIMIT 20,20;
# demand 3: Each page shows 20 Bar record , The... Is displayed 3 page
SELECT employee_id,last_name
FROM employees
LIMIT 40,20;
# demand : Each page shows pageSize Bar record , The... Is displayed pageNo page :
# The formula :LIMIT (pageNo-1) * pageSize,pageSize;
#2.2 WHERE ... ORDER BY ...LIMIT The order of declaration is as follows :
# commonly ORDER BY ...LIMIT Put it all at the end , And LIMIT Bottom line
# LIMIT The format of : Strictly speaking :LIMIT Position offset , Number of entries
# structure "LIMIT 0, Number of entries " Equivalent to "LIMIT Number of entries "
SELECT employee_id,last_name,salary
FROM employees
WHERE salary > 6000
ORDER BY salary DESC
#limit 0,10;
LIMIT 10;
# practice : There are 107 Data , We just want to show 32、33 What about this data ?
SELECT employee_id,last_name
FROM employees
LIMIT 31,2;
#2.3 MySQL8.0 New characteristics :LIMIT ... OFFSET ...
#LIMIT Row number OFFSET Offset
# practice : There are 107 Data , We just want to show 32、33 What about this data ?
SELECT employee_id,last_name
FROM employees
LIMIT 2 OFFSET 31;
# practice : Query the information of the highest paid employee in the employee table
SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary DESC
#limit 0,1
LIMIT 1;
#2.4 LIMIT It can be used in MySQL、PGSQL、MariaDB、SQLite And so on , Represents paging .
# Cannot be used in SQL Server、DB2、Oracle!
Multi-table query
One 、 Multi-table query , Also known as associative queries , It means that two or more tables complete the query operation together .
Two 、 There is a relationship between these tables queried together ( one-on-one 、 One to many ), There must be associated fields between them , This associated field may establish a foreign key , Or you may not have established a foreign key . such as : Employee table and department table , These two tables depend on “ Department number ” Association .
3、 ... and 、 If there is no multi table query , We would like to query the name of the employee ’Abel’ Which city do people work in , You need to query in the employee table first ’Abel’ Information about , I found him there 80 department , Then go to the Department table to query 80 Department Information , got it 80 The code where the Department is located is 2500, Then go again. locations The query code in the table is 2500 The address of :
SELECT *
FROM employees
WHERE last_name = 'Abel';
SELECT *
FROM departments
WHERE department_id = 80;
SELECT *
FROM locations
WHERE location_id = 2500;
Four 、 Use multi table query to query employee name and department name :
SELECT last_name, department_name
FROM employees, departments;
Query out 2889 Bar record , Check separately employees and departments I found that every employee matched every department , We call this case the Cartesian product error .
SELECT *
FROM employees; #107 Bar record
SELECT 2889 / 107
FROM DUAL;# 27
SELECT *
FROM departments; # 27 Bar record
5、 ... and 、SQL92 in , Cartesian product is also called cross connection , English is CROSS JOIN. stay SQL99 It is also used in CROSS JOIN Means cross connect . Its function is to connect any table , Even if the two tables are not related . stay MySQL Cartesian product will appear in the following cases :
SELECT employee_id,department_name
FROM employees CROSS JOIN departments;# Query out 2889 Bar record
6、 ... and 、 The error of Cartesian product will occur under the following conditions :
- Omit join conditions for multiple tables ( Or related conditions )
- Connection condition ( Or related conditions ) Invalid
- All rows in all tables are interconnected
7、 ... and 、 To avoid Cartesian product , Can be in WHERE Add a valid connection condition , Format :
SELECT Name 1, Name 2
FROM surface 1, surface 2
WHERE surface 1. Name 1 = surface 2. Name 2; # Connection condition
The above query code is changed to :
SELECT employee_id,department_name
FROM employees,departments
# Join condition of two tables
WHERE employees.`department_id` = departments.department_id;
8、 ... and 、 If there are fields in multiple tables in the query statement , You must specify the table where this field is located , For example, we need to check department_id This field , This field is employees and departments Associated fields , Both watches have , So at this point, we need to specify which table to look up department_id
SELECT employee_id,department_name,employees.department_id
FROM employees,departments
WHERE employees.`department_id` = departments.department_id;
Nine 、 from sql Optimization angle , It is recommended to query multiple tables , Each field is preceded by the table in which it is located , So the above code is suggested to be written as :
SELECT employees.employee_id,departments.department_name,employees.department_id
FROM employees,departments
WHERE employees.`department_id` = departments.department_id;
Ten 、 You can alias a table , stay SELECT and WHERE Aliases for tables used in .
SELECT emp.employee_id,dept.department_name,emp.department_id
FROM employees emp,departments dept
WHERE emp.`department_id` = dept.department_id;
If you alias a table , Once in a SELECT or WHERE If table names are used in , You must use the alias of the table , Instead of using the original name of the table , This is because when the code executes , Execute first FROM employees emp,departments dept, He knows that when you alias a table, you overwrite the original table name with an alias , In the future, he only knew aliases . The following operation is wrong :
SELECT emp.employee_id,departments.department_name,emp.department_id
FROM employees emp,departments dept
WHERE emp.`department_id` = departments.department_id;
11、 ... and 、 If there is n Multiple tables realize the query of multiple tables , At least n-1 Connection conditions , And for each connection condition AND Connect . For example, query employee's employee_id、last_name、department_name、city
SELECT e.employee_id,e.last_name,d.department_name,l.city,e.department_id,l.location_id
FROM employees e,departments d,locations l
WHERE e.`department_id` = d.`department_id`
AND d.`location_id` = l.`location_id`;
Twelve 、 Classification of multi table query
- angle 1: Equivalent connection vs Non equivalent connection
- angle 2: Self join vs Non self connecting
- angle 3: Internal connection vs External connection
Non equivalent connection
One 、 All of what we said earlier are equivalent connections , Used in connection conditions = Join the fields of two tables :WHERE emp.department_id = dept.department_id;, no need = What is connected is non equivalent connection
Two 、 Now we want to query the salary level of the employee , The code is as follows :
SELECT e.last_name,e.salary,j.grade_level
FROM employees e,job_grades j
#where e.`salary` between j.`lowest_sal` and j.`highest_sal`;
WHERE e.`salary` >= j.`lowest_sal` AND e.`salary` <= j.`highest_sal`;
Self join
One 、 Self join :
Two 、 If I want to inquire employees Employees in the table id, The name of the employee and the of his / her manager id And name , Then I need to alias employees The table is virtualized into two tables to represent different meanings , Then the two tables are connected internally , External connection and other queries :
SELECT emp.employee_id,emp.last_name,mgr.employee_id,mgr.last_name
FROM employees emp ,employees mgr
WHERE emp.`manager_id` = mgr.`employee_id`;
Internal connection
One 、 Internal connection : Merging rows of more than two tables with the same column , There are no rows in the result set that do not match one table with another . In other words, we only find the data that meets the query conditions , Other data are not required
SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id; # Only 106 Bar record
Two 、 External connection : In addition to the rows that meet the connection conditions, the two tables also return the left ( Or right ) Rows in the table that do not meet the criteria , This connection is called left ( Or right ) External connection . When there are no matching rows , The corresponding column in the result table is empty (NULL). In other words, the external connection is to find out the data that does not meet the conditions , If you find out what does not meet the conditions in the left table, it is called left outer join , If you find out what does not meet the conditions in the right table , It is called right outer connection , If the left and right tables are not satisfied with the body, ah Jian's have been found , Full connection
- If it's a left outer connection , The table on the left of the join condition is also called the main table , The table on the right is called the slave table .
- If it's a right outer connection , The table on the right in the join condition is also called the master table , The table on the left is called the slave table .
SQL92 Syntax to implement inner connection : See above , A little
SQL92 Syntax implementation external connection :
One 、 stay SQL92 Used in (+) Represents the location of the slave table . That is, in the left or right outer connection ,(+) Indicates which is from the table .
Two 、 stay SQL92 in , Only the left outer connection and the right outer connection , Not full ( Or all ) External connection .
3、 ... and 、MySQL I won't support it SQL92 The writing of Chinese and foreign connections in grammar !Oracle Support
# I won't support it :
SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id(+);
Write after the table with less data
(+)
SQL99 Syntax to implement multi table query
One 、SQL99 Use... In grammar JOIN ...ON To realize the query of multiple tables . This method can also solve the problem of external connection .MySQL It supports this way .
SELECT table1.column, table2.column,table3.column
FROM table1
JOIN table2 ON table1 and table2 The connection condition of
JOIN table3 ON table2 and table3 The connection condition of
explain :
- keyword
JOIN、INNER JOIN、CROSS JOINequally , Are used for internal connection - have access to
ONClause specifies additional join conditions . - This connection condition is separate from other conditions .
#SQL99 Syntax to implement inner connection :
SELECT last_name,department_name
FROM employees e INNER JOIN departments d
ON e.`department_id` = d.`department_id`;
SELECT last_name,department_name,city
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`
JOIN locations l
ON d.`location_id` = l.`location_id`;
Two 、SQL99 Syntax implementation external connection :
# practice : Query all employees last_name,department_name Information
# The left outer join :
SELECT last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Right connection :
SELECT last_name,department_name
FROM employees e RIGHT OUTER JOIN departments d
ON e.`department_id` = d.`department_id`;
LEFT JOINEquate toLEFT OUTER JOINRIGHT JOINEquate toRIGHT OUTER JOIN
MySQL Full external connection is not supported FULL JOIN, But you can useLEFT JOIN UNION RIGHT JOINInstead of
UNION Use
Merge query results using UNION keyword , You can give more than one SELECT sentence , And combine their results into a single result set . When merging , The number of columns and data types of the two tables must be the same , And correspond to each other . each SELECT Use... Between statements UNION or UNION ALL Keyword separation .
SELECT column,... FROM table1
UNION [ALL]
SELECT column,... FROM table2
explain :
UNIONOperator returns the union of the result sets of two queries , Remove duplicate records .UNION ALLOperator returns the union of the result sets of two queries . For duplicate parts of two result sets , No weight removal .- perform
UNION ALLStatement requires more resources thanUNIONFew statements , becauseUNION ALLWill redo the merged results . If you know clearly that there is no duplicate data in the result data after data consolidation , Or you don't need to remove duplicate data , Try to useUNION ALLsentence , To improve the efficiency of data query .
7 Kind of JOIN The implementation of the

# Chinese : Internal connection
SELECT employee_id,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`;
# Top left : The left outer join
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Top right : Right connection
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Middle left :
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL;
# Middle right :
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;
# Bottom left : Full outer join
# The way 1: Top left UNION ALL Middle right
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;
# The way 2: Middle left UNION ALL Top right
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Bottom right : Middle left UNION ALL Middle right
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;
SQL99 New features of grammar
Natural join
NATURAL JOIN: We can understand natural connection as SQL92 The equivalent connection in . It will help you automatically query all the same fields in the two connection tables , Then make equivalent connection :
SELECT employee_id,last_name,department_name
FROM employees e NATURAL JOIN departments d;
Equate to SQL92 In the standard :
SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`
AND e.`manager_id` = d.`manager_id`;
USING Connect
One 、 have access to USING Specify the fields with the same name in the data table for equivalent connection . But only with JOIN Use it together .
SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
USING (department_id);
Equate to SQL92 In the standard :
SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
ON e.department_id = d.department_id;
Two 、USING Connection and natural connection NATURAL JOIN The difference is ,USING Specifies the specific same field name , You need to USING The brackets of () Fill in the field with the same name to be specified . Use at the same time JOIN...USING Can be simplified JOIN ON Equivalent connection .
3、 ... and 、 There are three ways to constrain table joins :WHERE,ON,USING
WHERE: Applicable to all associated queriesON: And the onlyJOINUse it together , Only association conditions can be written . Although Association conditions can be combined toWHEREWrite... With other conditions , But it's better to write separately .USING: And the onlyJOINUse it together , Moreover, the names of the two associated fields should be consistent in the associated table , And it can only mean that the associated field values are equal
边栏推荐
- C# 游戏雏形 人物地图双重移动
- ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 2 - IMU initialization
- VINS理論與代碼詳解4——初始化
- How to write a global notice component?
- Lua table operation
- Click to unlock "keyword" of guanghetong 5g module
- 自动化运维必备的工具-Shell脚本介绍
- RSA a little bit of thought
- ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 1 - IMU flow pattern pre integration
- AEC of the three swordsmen in audio and video processing: the cause of echo generation and the principle of echo cancellation
猜你喜欢

ORB_SLAM2视觉惯性紧耦合定位技术路线与代码详解3——紧耦合优化模型

VINS理论与代码详解4——初始化

The product design software figma cannot be used. What software with similar functions is available in China

Technology sharing | quick intercom, global intercom

Information theory and coding 2 final review BCH code

港大、英伟达 | Factuality Enhanced Language Models for Open-Ended Text Generation(用于开放式文本生成的事实性增强语言模型)

姿态估计之2D人体姿态估计 - Numerical Coordinate Regression with Convolutional Neural Networks(DSNT)

这几个垂直类小众导航网站,你绝对不会想错过

VINS理论与代码详解0——理论基础白话篇

【高代码文件格式API】上海道宁为您提供文件格式API集——Aspose,只需几行代码即可创建转换和操作100多种文件格式
随机推荐
【无标题】
这几个垂直类小众导航网站,你绝对不会想错过
企业如何提升文档管理水平
AEC of the three swordsmen in audio and video processing: the cause of echo generation and the principle of echo cancellation
Odoo authority management (access authority and record rules) is applied to upgrade role management
Jiabo gp2120tu label printer installation and use tutorial (PC)
After class assignment for module 8 of phase 6 of the construction practice camp
如何構建以客戶為中心的產品藍圖:來自首席技術官的建議
Problems with database creation triggers
Recommend an easy-to-use designer navigation website
Guanghetong cooperates with China Mobile, HP, MediaTek and Intel to build 5g fully connected PC pan terminal products
姿态估计之2D人体姿态估计 - Human Pose Regression with Residual Log-likelihood Estimation(RLE)[仅链接]
产品设计软件Figma用不了,国内有哪些相似功能的软件
ORB_SLAM2视觉惯性紧耦合定位技术路线与代码详解1——IMU流型预积分
广和通高算力智能模组为万亿级市场5G C-V2X注智
22. Generate Parentheses
智能电网终极Buff | 广和通模组贯穿“发、输、变、配、用”全环节
竟然还有人说ArrayList是2倍扩容,今天带你手撕ArrayList源码
Guanghetong high computing power intelligent module injects intelligence into 5g c-v2x in the trillion market
QT 基于QScrollArea的界面嵌套移动