Home >Database >Mysql Tutorial >How to use logical operators when creating MySQL views?
#MySQL views can be created by using logical operators such as AND, OR and NOT. It can be explained by the following example −
We know that logical AND operator compares two expressions and returns true if both expressions are true. In the example below, we create a view based on the 'AND' operator.
The base table is Student_info with the following data −
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'); Query OK, 0 rows affected (0.13 sec) mysql> Select * from Info; +------+-------+---------+-----------+ | ID | Name | Address | Subject | +------+-------+---------+-----------+ | 133 | Mohan | Delhi | Computers | +------+-------+---------+-----------+ 1 row in set (0.00 sec)
We know that the logical OR operator compares Two expressions, returns true if at least one of them is true. In the following example, we will create a view with a condition based on the "OR" operator.
mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info WHERE (Subject = 'Computers' OR ADDRESS = 'Amritsar'); 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 | | 133 | Mohan | Delhi | Computers | +------+---------+----------+-----------+ 4 rows in set (0.00 sec)
NOT is the only operator that accepts only one operand. Returns 0 if the operand is TRUE; returns 1 if the operand is FALSE. In the following example, we will create a view with a condition based on the "NOT" operator.
mysql> Create or Replace View Info AS select ID, Name, Address , Subject FROM Student_info WHERE Subject != 'Computers'; Query OK, 0 rows affected (0.06 sec) 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)
The above is the detailed content of How to use logical operators when creating MySQL views?. For more information, please follow other related articles on the PHP Chinese website!