If we want to create a view that gets values from a table based on some specific conditions, then we must use the WHERE clause while creating the view. The value depending on the WHERE clause will be stored in the view. The syntax for creating a MySQL view using the WHERE clause is as follows -
Create View view_name AS Select_statements FROM table WHERE condition(s);
To illustrate the above concept, we use the following data from the table "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)
Now, with the help of the following query, we will create the view name "Info" with the condition of storing rows with only Computer as subject. So, we need to use WHERE clause while creating the view as shown below -
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)
The above is the detailed content of How to create a MySQL view that gets values from a table based on certain conditions?. For more information, please follow other related articles on the PHP Chinese website!