MySQL-UNION and LIMIT

MySQL self-learning route


Database used- link address

UNION

Overview

  • The UNION operator is used to combine the result sets of two or more SELECT statements
  • The SELECT statement inside UNION must have the same number of columns , and the columns have similar data types (not necessarily the same); the names of the fields after UNION are subject to the first SQL
  • UNION is the union operation on the data, the default deduplication, and the default sorting
  • UNION ALL is fast in efficiency . UNION ALL is a union operation on the data, without deduplication and sorting
  • If you want to use ORDER BY or LIMIT clauses to classify or limit all UNION results, you should add parentheses to a single SELECT statement, and put ORDER BY or LIMIT after the last SELECT

LIMIT

Overview

  • LIMIT is unique to MySQL, not in other databases, and not universal (the same mechanism in Oracle is called ROWNUM)
  • The LIMIT clause can be used to force the SELECT statement to return the specified number of records. LIMIT accepts 1 or 2 numeric parameters, which must be an integer constant
  • grammar:
LIMIT 偏移量,行数

The offset starts from 0, which means that the number of rows in the first record
starts from the offset +1, which means that the number of rows is taken

LIMIT 3,4 /*取出第4条至第7条,4条记录*/
  • In order to retrieve all rows from a certain offset to the end of the record set, you can specify the second parameter as -1
LIMIT n,-1
  • If only one parameter is given, it means to return the maximum number of rows
LIMIT n

LIMIT n is equivalent to LIMIT 0,n

LIMIT pagination

  • Each page displays pageSize records:
    pageNo page: (pageNo-1)*pageSize,pageSize
    LIMIT (pageNo-1)*pageSize,pageSize
  • The further the page is to be paged, the greater the offset of the LIMIT statement will be, and the speed will be significantly slower. At this time, the paging efficiency can be improved by subquery
SELECT a FROM A WHERE a.id = 1 ORDER BY id LIMIT 10000, 10

Optimize through subquery:

SELECT a FROM A WHERE  id >= (SELECT id FROM A  WHERE a.id = 1 ORDER BY id LIMIT 10000, 1) LIMIT 10

Guess you like

Origin blog.csdn.net/LvJzzZ/article/details/109002019