24. Union query in MySQL (UNION)

1 Introduction

Joint query is a way of multi-table query, which is often used in the operation of splitting tables . In the case of ensuring the same number of query fields in multiple SELECT statements, the results of multiple queries are combined.

grammar

1 SELECT2 UNION [ALL | DISTINCT] SELECT3 [UNION [ALL | DISTINCT] SELECT …];

UNION is the key word to realize joint query.

ALL means to save all query results.

DISTINCT is the default value, which can be omitted, which means removing completely duplicate records

2. Preparation

 1 CREATE DATABASE mahaiwuji;
 2 
 3 USE mahaiwuji;
 4 
 5 CREATE TABLE student1 (
 6     sid INT (4) PRIMARY KEY,
 7     sname VARCHAR (36),
 8     score INT
 9 ) ENGINE = INNODB DEFAULT CHARSET = utf8;
10 
11 INSERT INTO student1 VALUES (1,'a1',60);
12 INSERT INTO student1 VALUES (2,'a2',65);
13 INSERT INTO student1 VALUES (3,'a3',70);
14 INSERT INTO student1 VALUES (4,'a4',75);
15 INSERT INTO student1 VALUES (5,'a5',80);
16 
17 
18 CREATE TABLE student2 (
19     sid INT (4) PRIMARY KEY,
20     sname VARCHAR (36),
21     score INT
22 ) ENGINE = INNODB DEFAULT CHARSET = utf8;
23 
24 INSERT INTO student2 VALUES (5,'a5',80);
25 INSERT INTO student2 VALUES (6,'a6',85);
26 INSERT INTO student2 VALUES (7,'a7',90);
27 INSERT INTO student2 VALUES (8,'a8',95);
28 INSERT INTO student2 VALUES (9 , ' a9 ' , 100 );

3. Case

1  - Automatically remove completely duplicate data 
2  SELECT  *  FROM student1
 3  UNION 
4  SELECT  *  FROM student2;

. 1  - merging all data 
2  the SELECT  *  the FROM student1
 . 3  the UNION  ALL 
. 4  the SELECT  *  the FROM STUDENT2;

. 1  - combining section data 
2  the SELECT  *  the FROM student1 the WHERE SID = . 1 
. 3  the UNION  ALL 
. 4  the SELECT  *  the FROM STUDENT2;

1 -- 排序
2 SELECT * FROM student1
3 UNION ALL
4 SELECT * FROM student2
5 ORDER BY sid DESC;

Guess you like

Origin www.cnblogs.com/mahaiwuji/p/12702940.html