How to implement select Top N in MySQL

Source: Internet
Author: User
Tags mssql server

A friend of Access MSSQL server might be using MySQL to query the top N records. Custom uses the select top N form of the statement, here to explain that MySQL does not have this syntax, MySQL with limit to achieve the relevant functions, and more powerful, good. The following is an explanation of the use of LIMIT in MySQL:  
Syntax:
SELECT * FROM table LIMIT [offset,] rows | Rows offset offset
LIMIT clause can be used to force SEL The ECT statement returns the specified number of records. LIMIT accepts one or two numeric parameters. parameter must be an integer constant.
Given two parameters, the first parameter specifies the offset of the first return record row, and the second parameter specifies the maximum number of rows to return records. The offset of the
initial record line is 0 (not 1): MySQL also supports syntax: LIMIT # offset # In order to be compatible with PostgreSQL.
mysql> SELECT * FROM table LIMIT 5, 10;///Retrieve record line 6-15, note 10 is offset  
//In order to retrieve all record rows from an offset to the end of the recordset, you can specify that the second parameter is-1:
mysql> SELECT * from table LIMIT 95,-1;//retrieve record line 96-last.
//If only one parameter is given, it represents the maximum number of record rows returned:
mysql> SELECT * from table LIMIT 5;//Retrieving the first 5 record lines//In other words, limit n is equivalent to limit 0,n.
If you want to get the last few data you can add an ORDER by id desc

MySQL does not support the syntax of select top N and should be replaced with this:
SELECT * FROM tablename ORDER by OrderField DESC/ASC limit position, counter;
Position indicates where to start the query, and if 0 is the beginning, counter represents the number of queries
Take the first 15 records:
SELECT * FROM tablename ORDER by OrderField DESC/ASC limit 0,15

How to implement select Top N in MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.