MySQL syntax, UNION merge query result set, split a piece of data into multiple pieces and add a custom field to the query result

UNION syntax:

The MySQL UNION operator is used to combine the results of two or more SELECT statements into one result set. Multiple SELECT statements will remove duplicate data

SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION [ALL | DISTINCT]
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

parameter

  • expression1, expression2, ... expression_n : Columns to retrieve.

  • tables:  The data tables to retrieve.

  • WHERE conditions:  optional, search conditions.

  • DISTINCT:  Optional, delete duplicate data in the result set. By default, the UNION operator has already removed duplicate data, so the DISTINCT modifier has no effect on the result.

  • ALL:  Optional, returns all result sets, including duplicate data.

A piece of data is split into multiple pieces

A piece of data is split into 2 pieces according to the type of the custom field, and the union operator is used to merge the data, and the merged result set is sorted, conditional query, and paginated

SELECT * FROM(
	(SELECT id as uId, name as uName, age as uAge, 1 as type FROM user)
	union all
	(SELECT id, name, age, 2 as type FROM user)
) con where uAge > 0 
ORDER BY uAge desc 
limit 0, 10	

Table data:

 

Guess you like

Origin blog.csdn.net/qq_44695727/article/details/112557688