Home > Database > Mysql Tutorial > How can we create a MySQL view using subquery?

How can we create a MySQL view using subquery?

王林
Release: 2023-09-15 19:13:10
forward
961 people have browsed it

我们如何使用子查询创建 MySQL 视图?

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)
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template