MySQL---the use of Union

Source: Internet
Author: User

Union is simple enough to combine the result set of two SQL

Syntax: SQL1 UNION SQL2

Present a price list

Requirements: Find the price below 2000 and the price is higher than 3000 goods, can not use OR and not Between......and

idea: We can find a product below 2000 to get the result set 1

Find more than 3000 of the product to get the result set 2

Re-use Union to merge result set 1 and result set 2



When will I be allowed to use union?

A: You can use the same number of columns as two result sets, even if the field types are different.


The first result set has 2 columns, the second result set has 1 columns, and prompts to prompt for a different number of columns after the run.



The number of columns is the same, but the field types are different. such as Goods_name is a character type and goods_id is cosmetic, but can also be union. It is important to note that the name of the field after the Union is the first SQL


About the sort of union


The visible inner sort does not work, so now try to sort the outer layers


Visible outer sort has played a role

That is not the inner layer of the sort is useless, in fact, a different angle to think about the inner layer of the first sort, the outer order, the obvious inner layer sort seems redundant, so MySQL optimized the SQL statement, do not let the inner layer sort function. In order for the inner sort to work, the results of the inner order must be affected. such as: Plus limit


So that the inner layer sort would work.


What happens if you have repeated rows two times?

Create a further 2 tables,

Table A

Table B


Table A and Table B have two identical records ' Harry ', ' small high '

Now use union to look at the results


You can see that ' Harry ' and ' Little high ' have only one record, so another record is overwritten, so you can use union ALL if you want to not be overwritten.


, ' Harry ' and ' little high ' are not covered

Related Article

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.