创建MySQL视图时如何使用逻辑运算符?
可以使用AND,OR和NOT等逻辑运算符创建MySQL视图。可以通过以下示例进行说明-
使用AND运算符的视图
众所周知,逻辑AND运算符会比较两个表达式,如果两个表达式均为true,则返回true。在下面的示例中,我们将创建一个具有基于“AND”运算符的条件的视图。
示例
基本表是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) mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info WHERE (Subject = 'Computers' AND ADDRESS = 'DELHI'); mysql> Select * from Info; +------+-------+---------+-----------+ | ID | Name | Address | Subject | +------+-------+---------+-----------+ | 133 | Mohan | Delhi | Computers | +------+-------+---------+-----------+ 1 row in set (0.00 sec)
使用OR运算符的视图
众所周知,逻辑OR运算符会比较两个表达式,如果至少一个表达式为true,则返回true。在以下示例中,我们将创建一个具有基于“或”运算符的条件的视图。
示例
mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info WHERE (Subject = 'Computers' OR ADDRESS = 'Amritsar'); mysql> Select * from Info; +------+---------+----------+-----------+ | ID | Name | Address | Subject | +------+---------+----------+-----------+ | 101 | YashPal | Amritsar | History | | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | | 133 | Mohan | Delhi | Computers | +------+---------+----------+-----------+ 4 rows in set (0.00 sec)
使用NOT运算符的视图
NOT是唯一只使用一个操作数的运算符。如果操作数为TRUE,则返回0;如果操作数为FALSE,则返回1。在以下示例中,我们将创建一个具有基于“NOT”运算符的条件的视图。
示例
mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info WHERE Subject != 'Computers'; mysql> Select * from info; +------+---------+------------+------------+ | ID | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 132 | Shyam | Chandigarh | Economics | +------+---------+------------+------------+ 3 rows in set (0.00 sec)