Tạo view với subquery. Bảng Cars:
mysql> select * from cars;
+------+--------------+---------+
| ID | Name | Price |
+------+--------------+---------+
| 1 | Nexa | 750000 |
| 2 | Maruti Swift | 450000 |
| 3 | BMW | 4450000 |
| 4 | VOLVO | 2250000 |
| 5 | Alto | 250000 |
| 6 | Skoda | 1250000 |
| 7 | Toyota | 2400000 |
| 8 | Ford | 1100000 |
+------+--------------+---------+
8 rows in set (0.08 sec)
Tạo view cars_avgprice lấy xe có giá > trung bình (subquery trong ngoặc):
mysql> Create view cars_avgprice AS SELECT NAME, Price FROM Cars WHERE price > (SELECT AVG(Price) from cars);
Query OK, 0 rows affected (0.12 sec)
mysql> Select * from cars_avgprice;
+--------+---------+
| NAME | Price |
+--------+---------+
| BMW | 4450000 |
| VOLVO | 2250000 |
| Toyota | 2400000 |
+--------+---------+
3 rows in set (0.03 sec)
Chạy subquery riêng để hiểu:
mysql> Select AVG(Price) from cars;
+--------------+
| AVG(Price) |
+--------------+
| 1612500.0000 |
+--------------+
1 row in set (0.00 sec)
View chỉ chứa xe giá > 1.612.500.