MySQL selects data from two tables and sorts data in a unified manner

Source: Internet
Author: User
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:

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:

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 1

Union

Select 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

) Union

Select 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. But there is still an error, 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 union

Select id, title from subjects where id <# some_id # order by id limit 1

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.