首頁 >資料庫 >mysql教程 >在建立 MySQL 視圖時如何使用邏輯運算子?

在建立 MySQL 視圖時如何使用邏輯運算子?

王林
王林轉載
2023-08-25 15:05:071206瀏覽

在创建 MySQL 视图时如何使用逻辑运算符?

MySQL視圖可以透過使用邏輯運算子如AND、OR和NOT來建立。可以透過以下範例進行說明 −

使用AND運算子的視圖

我們知道邏輯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 運算子的視圖

我們知道,邏輯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 運算子的視圖

#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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除