How to use union in mysql

下次还敢
Release: 2024-04-26 05:07:46
Original
276 people have browsed it

In MySQL, the UNION operator merges result sets from multiple tables or subqueries, returning only unique result rows. It is primarily used to merge disjoint result sets and allows retaining duplicate rows via UNION ALL.

How to use union in mysql

UNION usage in MySQL

UNIONoperator is used in MySQL to merge from Result set of multiple tables or subqueries. It only returns unique result rows without repeating the same rows.

Syntax:

SELECT 列名1, 列名2, ... FROM 表名1 UNION SELECT 列名1, 列名2, ... FROM 表名2 ... [UNION ALL]
Copy after login

Parameters:

  • Column name: to be merged Column name. They must have the same order and data type.
  • Table name: The table or subquery to merge the result set.
  • UNION ALL(optional): Keep duplicate rows.

Usage:

UNION is mainly used to merge disjoint result sets from different tables or subqueries. It only keeps unique result rows.

For example, to merge the result sets of tablescustomersandordersand display each customer's information and order information, you can use the following query:

SELECT * FROM customers UNION SELECT * FROM orders;
Copy after login

If you want to keep duplicate rows, you can useUNION ALL:

SELECT * FROM customers UNION ALL SELECT * FROM orders;
Copy after login

Note:

  • The UNION operator only merges rows with the same Number of columns and data type of the result set.
  • If the column names are different, you need to use aliases or wildcards (*) to match them.
  • If columns have different data types, you need to use a conversion function (such asCAST()orCONVERT()) to ensure they are compatible. The
  • UNION operator does not consider sort order unless anORDER BYclause is used.

The above is the detailed content of How to use union in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!