如何使用多个表中的数据来创建一个 MySQL 视图?
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)
广告