如何透過在基本表中進行模式匹配來選擇資料,從而建立 MySQL 檢視?


MySQL LIKE 算符用於基於模式匹配來選擇資料。類似地,我們可以將 LIKE 算符與檢視一起使用,以基於基本表中的模式匹配來選擇特定資料。為了理解這個概念,我們使用基礎表“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)

示例

以下查詢將建立一個名為“資訊”的檢視,使用“LIKE”算符選擇一些特定值,這些值基於模式匹配 -

mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name LIKE '%Ra%';
Query OK, 0 rows affected (0.11 sec)

mysql> Select * from Info;
+------+--------+------------+------------+
| id   | Name   | Address    | Subject    |
+------+--------+------------+------------+
| 105  | Gaurav | Chandigarh | Literature |
| 125  | Raman  | Shimla     | Computers  |
| 130  | Ram    | Jhansi     |  Computers |
+------+--------+------------+------------+
3 rows in set (0.00 sec)

我們還可以將 NOT 與 LIKE 算符一起使用,如下所示 -

mysql> Create or Replace view Info AS SELECT * from student_info WHERE Name NOT LIKE'%Ra%';
Query OK, 0 rows affected (0.14 sec)

mysql> Select * from info;
+------+---------+------------+-----------+
| id   | Name    | Address    | Subject   |
+------+---------+------------+-----------+
| 101  | YashPal | Amritsar   | History   |
| 132  | Shyam   | Chandigarh | Economics |
| 133  | Mohan   | Delhi      | Computers |
+------+---------+------------+-----------+
3 rows in set (0.00 sec)

更新時間:22 - 六月 - 2020

121 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.