In MySQL, union, order by, and limit

Source: Internet
Author: User

I have a table

Create Table 'test1 '(
'Id' int (10) unsigned not null auto_increment,
'Name' varchar (20) not null,
'Desc' varchar (100) not null,
Primary Key ('id ')
) Engine = InnoDB default charset = utf8

 

(1) The following query will report an error: [err] 1221-Incorrect usage of union and order

Select * From test1 where name like 'a % 'order by name
Union
Select * From test1 where name like 'B %' order by name

Should be changed:

Select * From test1 where name like 'a %'
Union
Select * From test1 where name like 'B %' order by name

In Union, only one order by clause is allowed without parentheses (think about what if the column names of order by clause on both sides of union are different ), this sorts the Union result sets.

Or change:

(Select * From test1 where name like 'a % 'order by name)
Union
(Select * From test1 where name like 'B %' order by name)

The two order by statements are executed before Union.

 

(2) The same

Select * From test1 where name like 'a % 'limit 10
Union
Select * From test1 where name like 'B %' Limit 20

Equivalent

(Select * From test1 where name like 'a % 'limit 10)
Union
(Select * From test1 where name like 'B %') Limit 20

That is, the last limit acts on the result set after union, rather than the SELECT statement after union.

You can also add parentheses to get the expected results.

(Select * From test1 where name like 'a % 'limit 10)
Union
(Select * From test1 where name like 'B %' Limit 20)

 

(3) Difference between Union and Union all

Union filters out duplicate rows in the result set obtained by select on both sides of union, while union all does not filter out duplicate rows.

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.