Combination query-UNION

Combined query : MySQL allows you to execute multiple queries (multiple SELECT statements) and return the results as a single query result set. This combination and query also become a union or compound query

 

First, use the combination query UNION

You can use the UNION operator to combine several SQL queries,

To give an example: query a list of commodities whose price is less than 5, and also want to include all items produced by suppliers 1001 and 1002. First use the WHERE clause to complete this work.

SELECT vend_id,prod_id,prod_price 
FROM products 
WHERE prod_price <= 5 OR vend_id IN(1001,1002)

Next, we can use a combined query to achieve this function, UNION instructs MySQL to execute two SELECT statements, and the output is synthesized into a result set

SELECT vend_id,prod_id,prod_price
FROM products 
WHERE prod_price <= 5 
UNION
SELECT vend_id,prod_id,prod_price
FROM products
WHERE vend_id IN(1001,1002)

 

 Second, the line containing the cancellation of duplicates

UNION automatically removes duplicate rows from the query result set, which is the default behavior, because UNION always completes the same conditions as multiple WHERE clauses. To return all matching rows, you can use UNION ALL

SELECT vend_id,prod_id,prod_price
FROM products 
WHERE prod_price <= 5 
UNION ALL
SELECT vend_id,prod_id,prod_price
FROM products
WHERE vend_id IN(1001,1002)

 

 

3. UNION rules 

  •  UNION must consist of 2 or more SELECT statements
  • Each query in UNION must contain the same columns, expressions, or aggregate functions. But their order can be different
  • When sorting combined query results, they must be placed after the last SELECT clause because there are no two sorting methods for the result set
Published 156 original articles · Liked 34 · Visits 150,000+

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105558609