Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เราจะสร้างมุมมอง 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)