MySQL UNION 運算子可以組合兩個或多個結果集,因此我們可以使用 UNION 運算子建立一個包含多個表格資料的檢視。為了理解這個概念,我們使用具有以下資料的基底表「Student_info」和「Student_detail」 -
mysql> Select * from Student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | +------+---------+------------+------------+ 6 rows in set (0.00 sec) mysql> Select * from Student_detail; +-----------+-------------+------------+ | Studentid | StudentName | address | +-----------+-------------+------------+ | 100 | Gaurav | Delhi | | 101 | Raman | Shimla | | 103 | Rahul | Jaipur | | 104 | Ram | Chandigarh | | 105 | Mohan | Chandigarh | +-----------+-------------+------------+ 5 rows in set (0.00 sec)
下面的查詢將使用上述兩個表中的資料建立一個視圖-
mysql> Create or Replace View Info AS Select StudentName from Student_detail UNION Select Name From Student_info; Query OK, 0 rows affected (0.10 sec) mysql> select * from info; +-------------+ | StudentName | +-------------+ | Gaurav | | Raman | | Rahul | | Ram | | Mohan | | YashPal | | Shyam | +-------------+ 7 rows in set (0.00 sec)
上面的結果集包含兩個欄位中的值的組合。如果一個值重複,那麼它會消除重複的值。
我們也可以儲存所有值,也可以透過使用 UNION ALL 來重複一個值,如以下查詢所示 -
mysql> Create or Replace View Info AS Select student name from Student_detail UNION ALL Select Name From Student_info; Query OK, 0 rows affected (0.16 sec) mysql> select * from info; +-------------+ | StudentName | +-------------+ | Gaurav | | Raman | | Rahul | | Ram | | Mohan | | YashPal | | Gaurav | | Raman | | Ram | | Shyam | | Mohan | +-------------+ 11 rows in set (0.00 sec)
以上是如何使用多個表中的資料建立 MySQL 視圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!