1. 程式人生 > >mysql入門(union合併查詢結果十三)

mysql入門(union合併查詢結果十三)

1:union可以合併集合(相加)

  案例:查詢job包含MANAGER和包含SALESMAN的員工

 select empno,ename,job from emp where job in('MANAGER','SALESMAN');
+-------+---------+----------+
| empno | ename   | job      |
+-------+---------+----------+
|  7499 | ALLEN   | SALESMAN |
|  7521 | WARD    | SALESMAN |
|  7566 | JONES   | MANAGER  |
|  7654 | MARTIM  | SALESMAN |
|  7698 | BLAKE   | MANAGER  |
|  7844 | IUSRNER | SALESMAN |
+-------+---------+----------+
6 rows in set (0.00 sec)

2:採用union來合併(要求兩個查詢的欄位數量必須相等)

 select ename,job from emp where job='MANAGER' union select ename,job from emp where job='SALESMAN';
+---------+----------+
| ename   | job      |
+---------+----------+
| JONES   | MANAGER  |
| BLAKE   | MANAGER  |
| ALLEN   | SALESMAN |
| WARD    | SALESMAN |
| MARTIM  | SALESMAN |
| IUSRNER | SALESMAN |
+---------+----------+
6 rows in set (0.00 sec)

select ename,job from emp where job='MANAGER' union select ename,empno from emp where job='SALESMAN';
+---------+---------+
| ename   | job     |
+---------+---------+
| JONES   | MANAGER |
| BLAKE   | MANAGER |
| ALLEN   | 7499    |
| WARD    | 7521    |
| MARTIM  | 7654    |
| IUSRNER | 7844    |
+---------+---------+
6 rows in set (0.00 sec)