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

การสร้าง MySQL View จากหลายตารางด้วย UNION

ใช้ UNION (รวมผลลัพธ์ ลบซ้ำ) หรือ UNION ALL (รวมผลลัพธ์ เก็บซ้ำ) ในคำสั่ง CREATE VIEW เพื่อสร้าง View จากหลายตาราง

ตารางต้นทาง

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  |
+------+---------+------------+------------+

Student_detail

+-----------+-------------+------------+
| Studentid | StudentName | address    |
+-----------+-------------+------------+
| 100       | Gaurav      | Delhi      |
| 101       | Raman       | Shimla     |
| 103       | Rahul       | Jaipur     |
| 104       | Ram         | Chandigarh |
| 105       | Mohan       | Chandigarh |
+-----------+-------------+------------+

สร้าง View ด้วย UNION (ลบซ้ำ)

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 (Gaurav, Raman, Ram, Mohan ซ้ำ ถูกลบออก)

สร้าง View ด้วย UNION ALL (เก็บซ้ำ)

mysql> CREATE OR REPLACE VIEW Info AS
    SELECT StudentName 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 (มีค่าซ้ำ)

สรุป: UNION = DISTINCT (ลบซ้ำ), UNION ALL = ALL (เก็บทั้งหมด เร็วกว่า) คอลัมน์ที่ SELECT ต้องมีจำนวนและชนิดข้อมูลตรงกัน