Home  >  Article  >  Database  >  How to merge mysql query results

How to merge mysql query results

青灯夜游
青灯夜游Original
2022-01-24 18:00:0822388browse

In mysql, you can use the UNION operator to merge query results. This operator is used to merge the query results of more than two SELECT statements together, and then remove the same records; syntax "query statement" 1 union query statement 2 union....".

How to merge mysql query results

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

In mysql, you can use the UNION operator to merge query results.

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

Syntax:

查询语句1
union
查询语句2
union
....

Application scenarios:

The results to be queried come from multiple tables, and the multiple tables have no direct connection relationship, but the queried information is consistent

Features: ★

1. The number of query columns in multiple query statements is required to be consistent!

2. The type and order of each column of the query that requires multiple query statements should be consistent

3. The union keyword is deduplicated by default. If union all is used, duplicates can be included

Example: Query employee information whose department number is >90 or whose email address contains a

I will post screenshots and codes directly

##

#联合查询

#
SELECT * FROM employees WHERE department_id > 90 OR email LIKE '%a%';
#使用UNION联合查询
SELECT * FROM employees WHERE department_id > 90
UNION
SELECT * FROM employees WHERE email LIKE '%a%';

#
USE test;
#案例:查询中国用户中女性的信息以及外国用户中女性的用户信息
SELECT c.`c_id`, c.`c_name`, c.`c_sex` FROM china c WHERE c_sex = '女'
UNION
SELECT f.`f_id`, f.`f_name`, f.`f_sex` FROM foreignUser f WHERE f_sex = 'female';


#china表和foreignUser表中都有66号韩梅梅(UNION会去重)
SELECT c.`c_id`, c.`c_name` FROM china c WHERE c_sex = '女'
UNION
SELECT f.`f_id`, f.`f_name` FROM foreignUser f WHERE f_sex = 'female';

#china表和foreignUser表中都有66号韩梅梅(UNION ALL 不会去重)
SELECT c.`c_id`, c.`c_name` FROM china c WHERE c_sex = '女'
UNION ALL
SELECT f.`f_id`, f.`f_name` FROM foreignUser f WHERE f_sex = 'female';

USE UNION

Use UNION ALL

[Related recommendations:

mysql video tutorial]

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

Statement:
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