如果我們想創建一個視圖,根據某些特定條件從表中獲取值,那么我們必須在創建視圖時使用 WHERE 子句。取決于 WHERE 子句的值將存儲在視圖中。使用 WHERE 子句創建 MySQL 視圖的語法如下 –
語法
Create View view_name AS Select_statements FROM table WHERE condition(s);
登錄后復制
示例
為了說明上述概念,我們使用表“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 | +------+---------+------------+------------+ 4 rows in set (0.08 sec)
登錄后復制
現在,借助以下查詢,我們將創建視圖名稱“Info”,其條件是存儲僅以計算機作為主題的行。因此,我們在創建視圖時需要使用 WHERE 子句,如下所示 –
mysql> Create OR Replace VIEW Info AS Select Id, Name, Address, Subject from student_info WHERE Subject = 'Computers'; Query OK, 0 rows affected (0.46 sec) mysql> Select * from info; +------+-------+---------+-----------+ | Id | Name | Address | Subject | +------+-------+---------+-----------+ | 125 | Raman | Shimla | Computers | | 130 | Ram | Jhansi | Computers | +------+-------+---------+-----------+ 2 rows in set (0.00 sec)
登錄后復制
以上就是如何創建一個 MySQL 視圖,根據某些條件從表中獲取值?的詳細內容,更多請關注www.92cms.cn其它相關文章!