To illustrate how to create a MySQL view using a subquery, we use the following data from the "Cars" table -
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)
Now, the following query will use the subquery The query creates a view called "cars_avgprice" and the subquery will provide values to the view. Subqueries must be enclosed in parentheses.
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)
If we run the above subquery alone, we can understand how the view gets its value -
mysql> Select AVG(Price) from cars; +--------------+ | AVG(Price) | +--------------+ | 1612500.0000 | +--------------+ 1 row in set (0.00 sec)
That's why the view "cars_avgprice" contains prices that are higher than the average price (i.e. 1612500) Car List.
The above is the detailed content of How can we create a MySQL view using subquery?. For more information, please follow other related articles on the PHP Chinese website!