程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> 詳解MySQL中UNION的用法,詳解mysqlunion

詳解MySQL中UNION的用法,詳解mysqlunion

編輯:MySQL綜合教程

詳解MySQL中UNION的用法,詳解mysqlunion


如果想選擇其他幾個表中的行或從一個單一的表作為一個單獨的結果集行的幾個集會,那麼可以使用的UNION。

UNION在MySQL4.0以上版本才能可以使用。本節說明如何使用它。

假設有兩個表,潛在和實際的客戶列表,供應商購買耗材合並所有三個表中的姓名和地址,來創建一個單一的郵件列表。UNION提供了一種方法做到這一點。假設三個表有以下內容:

mysql> SELECT * FROM prospect;
+---------+-------+------------------------+
| fname | lname | addr     |
+---------+-------+------------------------+
| Peter | Jones | 482 Rush St., Apt. 402 |
| Bernice | Smith | 916 Maple Dr.   |
+---------+-------+------------------------+
mysql> SELECT * FROM customer;
+-----------+------------+---------------------+
| last_name | first_name | address    |
+-----------+------------+---------------------+
| Peterson | Grace  | 16055 Seminole Ave. |
| Smith  | Bernice | 916 Maple Dr.  |
| Brown  | Walter  | 8602 1st St.  |
+-----------+------------+---------------------+
mysql> SELECT * FROM vendor;
+-------------------+---------------------+
| company   | street    |
+-------------------+---------------------+
| ReddyParts, Inc. | 38 Industrial Blvd. |
| Parts-to-go, Ltd. | 213B Commerce Park. |
+-------------------+---------------------+

這不要緊,如果所有的三個表具有不同的列名。下面的查詢演示了如何選擇一下子從三個表的名稱和地址:

mysql> SELECT fname, lname, addr FROM prospect
-> UNION
-> SELECT first_name, last_name, address FROM customer
-> UNION
-> SELECT company, '', street FROM vendor;
+-------------------+----------+------------------------+
| fname    | lname | addr     |
+-------------------+----------+------------------------+
| Peter    | Jones | 482 Rush St., Apt. 402 |
| Bernice   | Smith | 916 Maple Dr.   |
| Grace    | Peterson | 16055 Seminole Ave. |
| Walter   | Brown | 8602 1st St.   |
| ReddyParts, Inc. |   | 38 Industrial Blvd. |
| Parts-to-go, Ltd. |   | 213B Commerce Park. |
+-------------------+----------+------------------------+

如果想選擇所有記錄,包括重復的,請ALL的第一個UNION關鍵字:

mysql> SELECT fname, lname, addr FROM prospect
-> UNION ALL
-> SELECT first_name, last_name, address FROM customer
-> UNION
-> SELECT company, '', street FROM vendor;
+-------------------+----------+------------------------+
| fname    | lname | addr     |
+-------------------+----------+------------------------+
| Peter    | Jones | 482 Rush St., Apt. 402 |
| Bernice   | Smith | 916 Maple Dr.   |
| Grace    | Peterson | 16055 Seminole Ave. |
| Bernice   | Smith | 916 Maple Dr.   |
| Walter   | Brown | 8602 1st St.   |
| ReddyParts, Inc. |   | 38 Industrial Blvd. |
| Parts-to-go, Ltd. |   | 213B Commerce Park. |
+-------------------+----------+------------------------+


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved