1. 程式人生 > 實用技巧 >MySQL資料庫之union聯合查詢

MySQL資料庫之union聯合查詢

聯合查詢(union)

MariaDB [sel]> create table resume(
    -> id tinyint unsigned auto_increment primary key,
    -> name varchar(20) not null,
    -> skill set('php','mysql','javascript')
    -> );
# `Query OK, 0 rows affected (0.023 sec)`

MariaDB [sel]> insert into resume values (null,'Kimmy',1),(null,'Jerry',3);
# `Query OK, 2 rows affected (0.009 sec)`
# `Records: 2  Duplicates: 0  Warnings: 0`

union的使用

  • 作用

    • 將多個select語句結果集縱向聯合起來
    • union可以將一個複雜的條件轉成兩個簡單的條件
  • 語法

    • select 語句 union [選項] select 語句 union [選項] select 語句
MariaDB [sel]> select name from grades union select name from resume;
+-------+
| name  |
+-------+
| Sunny |
| Jerry |
| Marry |
| Tommy |
| Kimmy |
+-------+
# `5 rows in set (0.008 sec)`
-- 方法一:where
mysql> select * from stu where (stuaddress='上海' and stusex='男') or (stuaddress='北京' and stusex='女');
+--------+---------+--------+--------+---------+------------+------+------+
| stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
+--------+---------+--------+--------+---------+------------+------+------+
| s25302 | 李文才   | 男     |    31 |       3 | 上海        |   77 |   76 |
| s25303 | 李斯文   | 女     |    22 |       2 | 北京        |   55 |   82 |
+--------+---------+--------+--------+---------+------------+------+------+
# `2 rows in set (0.00 sec)`

-- 方法二:union
mysql> select * from stu where stuaddress='上海' and stusex='男' union select * from stu where stuaddress='北京' and stusex='女';
+--------+---------+--------+--------+---------+------------+------+------+
| stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
+--------+---------+--------+--------+---------+------------+------+------+
| s25302 | 李文才  | 男      |     31 |       3 | 上海       |   77 |   76 |
| s25303 | 李斯文  | 女      |     22 |       2 | 北京       |   55 |   82 |
+--------+---------+--------+--------+---------+------------+------+------+
# `2 rows in set (0.00 sec)`

union的選項

  • union的選項有兩個
    • all 顯示所有資料
    • distinct 去除重複的資料[預設]
MariaDB [sel]> select name from grades union all select name from resume;
+-------+
| name  |
+-------+
| Sunny |
| Jerry |
| Marry |
| Tommy |
| Sunny |
| Kimmy |
| Jerry |
+-------+
# `7 rows in set (0.001 sec)`

union的注意事項

  • union兩邊的select語句的欄位個數必須一致
  • union兩邊的select語句的欄位名可以不一致,最終按第一個select語句的欄位名
  • union兩邊的select語句中的資料型別可以不一致