MySQL視圖可以透過使用邏輯運算子如AND、OR和NOT來建立。可以透過以下範例進行說明 −
我們知道邏輯AND運算子比較兩個表達式,如果兩個表達式都為真則傳回真。在下面的範例中,我們建立了一個基於'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'); 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)
我們知道,邏輯OR 運算子會比較兩個表達式,如果至少其中一個表達式為true,則傳回true。在下列範例中,我們將建立一個具有基於「OR」運算子的條件的視圖。
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 是唯一隻接受一個運算元的運算子。如果運算元為 TRUE,則傳回 0;如果運算元為 FALSE,則傳回 1。在以下範例中,我們將建立一個具有基於「NOT」運算符的條件的視圖。
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)#
以上是在建立 MySQL 視圖時如何使用邏輯運算子?的詳細內容。更多資訊請關注PHP中文網其他相關文章!