The Union clause in MySQL does not support the order by solution. The union clause

Source: Internet
Author: User

The Union clause in MySQL does not support the order by solution. The union clause

This example describes how the Union clause in MySQL does not support order. We will share this with you for your reference. The details are as follows:

I know very little about DB. This problem only happens in MySQL, and I don't know if other DBMS is the same.

The problem is that I want to obtain two adjacent rows with a row of records in a table and want to obtain them through union, so I write:

select id,title from subjects where id>#some_id# order by id limit 1unionselect id,title from subjects where id<#some_id# order by id limit 1

However, the error message "Incorrect usage of UNION and order by" appears ". It seems that union and order by cannot be used, but order by is indeed required here. Soon I came up with a work und:

select * from (select id,title from subjects where id>#some_id# order by id limit 1) unionselect id,title from subjects where id<#some_id# order by id limit 1

In terms of experience, the second clause will not be affected by union. order by can be used. So we can wrap the first clause in a bracket. However, an error still occurred, prompting "Every derived table must have its own alias ". The prompt here is that we need to get an alias for the temporary table generated in the brackets, which is much easier. So it is changed:

select * from (select id,title from subjects where id>#some_id# order by id limit 1) as t1 unionselect id,title from subjects where id<#some_id# order by id limit 1

If this statement is successfully executed and the correct result is obtained, write it down and forget it.

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.