为了说明如何使用子查询创建 MySQL 视图,我们使用“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)
现在,以下查询将使用子查询创建一个名为“cars_avgprice”的视图,该子查询将向视图提供值。子查询必须括在括号内。
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)
如果我们单独运行上面的子查询,我们可以理解视图如何获取其值 –
mysql> Select AVG(Price) from cars; +--------------+ | AVG(Price) | +--------------+ | 1612500.0000 | +--------------+ 1 row in set (0.00 sec)
这就是为什么视图“cars_avgprice”包含价格高于平均价格(即 1612500)的汽车列表。
原文来自:www.php.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容