当前位置:网站首页>Sorting and paging

Sorting and paging

2022-06-10 15:43:00 CaraYQ

Sorting data

One 、 Sort rule : Use ORDER BY Sort the queried data .

  1. Ascending :ASC( Default )
  2. 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 .
 Insert picture description here
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 :

  1. Omit join conditions for multiple tables ( Or related conditions )
  2. Connection condition ( Or related conditions ) Invalid
  3. 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_idlast_namedepartment_namecity

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

  1. angle 1: Equivalent connection vs Non equivalent connection
  2. angle 2: Self join vs Non self connecting
  3. 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 :
 Insert picture description here

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 :
 Insert picture description here
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

  1. 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 .
  2. 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 :

  1. keyword JOININNER JOINCROSS JOIN equally , Are used for internal connection
  2. have access to ON Clause specifies additional join conditions .
  3. 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 JOIN Equate to LEFT OUTER JOIN
RIGHT JOIN Equate to RIGHT OUTER JOIN
MySQL Full external connection is not supported FULL JOIN, But you can use LEFT JOIN UNION RIGHT JOIN Instead 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 :

  1. UNION Operator returns the union of the result sets of two queries , Remove duplicate records .
  2. UNION ALL Operator returns the union of the result sets of two queries . For duplicate parts of two result sets , No weight removal .
  3. perform UNION ALL Statement requires more resources than UNION Few statements , because UNION ALL Will 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 use UNION ALL sentence , To improve the efficiency of data query .

7 Kind of JOIN The implementation of the

 Insert picture description here

#  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

  1. WHERE: Applicable to all associated queries
  2. ON: And the only JOIN Use it together , Only association conditions can be written . Although Association conditions can be combined to WHERE Write... With other conditions , But it's better to write separately .
  3. USING: And the only JOIN Use 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
原网站

版权声明
本文为[CaraYQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101526281453.html