Use LIMIT instance in MySQLUNION

Source: Internet
Author: User
In mysql, union is used to merge the result sets of two or more SELECT statements. LIMIT is used to display the result sets by page. This article combines these two statements, describes how to use limit in union. Use LIMIT in MySQL UNION to LIMIT the number of returned Records. if you LIMIT the SELECT clause, you need to add parentheses for the SELECT statement:

(SELECT aid, title FROM article LIMIT 2) union all (SELECT bid, title FROM blog LIMIT 2)

This SQL statement returns two records of a SELECT statement. If parentheses are not added, the last LIMIT 2 will act on the entire UNION statement and a total of two records will be returned.

Similar to order by, when you need to LIMIT the entire UNION result, we recommend that you enclose the SELECT statements in parentheses to make the statements clearer:

(SELECT aid, title FROM article) union all (SELECT bid, title FROM blog) LIMIT 2

It can be seen that LIMIT and order by are often used together, and they are used in the same way in UNION.

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.