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中文网其他相关文章!