How can I create a MySQL view that takes the values from a table based on some condition(s)?

MySQLMySQLi Database

If we want to create a view that takes the values from a table based on some particular condition(s) then we have to use WHERE clause while creating the view. The values depending upon the WHERE clause will be stored in view. The syntax of creating a MySQL view with WHERE clause can be as follows −

Syntax

Create View view_name AS Select_statements FROM table WHERE condition(s);

Example

To illustrate the above concept, we are using the following data from 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 names ‘Info’ having the condition that it stores the rows having only computers as the subject. So we need to use WHERE clause as follows while creating the view −

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)
raja
Published on 22-Feb-2018 10:52:48
Advertisements