SQL statement Query Results Merge UNION ALL usage

Source: Internet
Author: User
Tags mysql version

Organize other people's SQL

Presumably the idea is to use Union and UNION ALL

--Merge duplicate rows
SELECT * FROM A
Union
SELECT * FROM B

--Do not merge duplicate rows
SELECT * FROM A
UNION ALL
SELECT * FROM B

Sort by a field
--Merge duplicate rows
SELECT *
From (
SELECT * FROM A
Union
SELECT * from B) as T
Order BY Field name

--Do not merge duplicate rows
SELECT *
From (
SELECT * FROM A
UNION ALL
SELECT * from B) as T
Order BY Field name

SQL Server Edition
Select * FROM (
Select top 2 id,adddate,title,url from barticle where classid= ' 1 ' ORDER by adddate Desc) A
Union All
Select * FROM (
Select top 2 id,adddate,title,url from barticle where classid= ' 2 ' ORDER by adddate Desc) B
Union All
Select * FROM (
Select top 2 id,adddate,title,url from barticle where classid= ' 3 ' ORDER by adddate Desc) C
Union All
Select * FROM (
Select top 2 id,adddate,title,url from barticle where classid= ' 4 ' ORDER by adddate Desc) D

MySQL version
Select * FROM (
Select Id,adddate,title,url from barticle where classid= ' 1 ' ORDER by adddate desc limit 0,2) A
Union All
Select * FROM (
Select Id,adddate,title,url from barticle where classid= ' 2 ' ORDER by adddate desc limit 0,2) B
Union All
Select * FROM (
Select Id,adddate,title,url from Barticle where classid= ' 3 ' ORDER by adddate desc limit 0,2) C
Union All
Select * FROM (
Select Id,adddate,title,url from Barticle where classid= ' 4 ' ORDER by adddate desc limit 0,2) D
Http://blog.csdn.net/kemy88/archive/2007/02/28/1516913.aspx

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.