The method used by union and order by in MySQL

Source: Internet
Author: User

The Union and order by in MySQL can be used together, but there are some minor problems to be aware of in use, as illustrated by the examples below. First look at the T1 table below.

1, if directly with the following SQL statement will be error: incorrect usage of UNION and ORDER by.

SELECT * from T1 WHERE username like ' l% ' ORDER by score ASC
UNION
SELECT * from T1 WHERE username like '%m% ' ORDER by score ASC

Because the Union can use only one order by without parentheses, there are 2 ways to modify this statement. As follows:

(1) The previous order by can be removed and changed to the following:

SELECT * from T1 WHERE username like ' l% '
UNION
SELECT * from T1 WHERE username like '%m% ' ORDER by score ASC

The SQL means union first and then order by for the entire result set.

(2) can be changed to the following by two queries, respectively, by parentheses:

(SELECT * from T1 WHERE username like ' l% ' ORDER by Sroce ASC)
UNION
(SELECT * from T1 WHERE username like '%m% ' ORDER by score ASC)

The purpose of this approach is to have the two result sets first order by, and then union the two result sets. But you will find that this is not an error, but the two order by does not work, so it should be changed as follows:

SELECT * FROM
(SELECT * from T1 WHERE username like ' l% ' ORDER by score ASC) T3
UNION
SELECT * FROM
(SELECT * from T1 WHERE username like '%m% ' ORDER by score ASC) T4

In other words, an order by cannot appear directly in the Union clause, but it can appear in the clause of the clause.

2. By the way, the difference between Union and union all.

Union filters out duplicate rows in two result sets, and union all does not filter out duplicate rows.

The method used by union and order by in MySQL

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.