我们如何通过从基础表中选择一定范围的数据来创建一个 MySQL 视图?
众所周知,MySQL BETWEEN 运算符可用于从某些取值范围内选择值。我们可以将 BETWEEN 运算符与视图结合起来,从基础表中选择某个取值范围。为了理解该概念,我们使用包含以下数据的基础表“student_info”——
mysql> Select * from 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 | +------+---------+------------+------------+ 6 rows in set (0.00 sec)
示例
以下查询将通过使用“BETWEEN”运算符创建一个名为“Info”的视图,在特定范围内选择某些值——
mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name BETWEEN 'C' AND 'P'; Query OK, 0 rows affected (0.14 sec) mysql> Select * from info; +------+--------+------------+------------+ | id | Name | Address | Subject | +------+--------+------------+------------+ | 105 | Gaurav | Chandigarh | Literature | | 133 | Mohan | Delhi | Computers | +------+--------+------------+------------+ 2 rows in set (0.00 sec)
同样,我们可以将 BETWEEN 运算符与 NOT 结合使用,来选择与我们在查询中编写的不同的取值范围——
mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name NOT BETWEEN 'C' AND 'P'; Query OK, 0 rows affected (0.06 sec) mysql> Select * from Info; +------+---------+------------+-----------+ | id | Name | Address | Subject | +------+---------+------------+-----------+ | 101 | YashPal | Amritsar | History | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | +------+---------+------------+-----------+ 4 rows in set (0.00 sec)
广告