MySQL Tutorial
A view is a virtual table based on the result-set of an MySQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
A view summarize data from various tables can be used to generate reports.
You can add MySQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Let's perform the view operation on a database table.
Consider we've an Students table in our database with the following records:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | C++ |
2 | SAM | JAVA |
3 | Sara | HTML | 4 | Rim | Java |
5 | Micheal | MySQL |
6 | Lara | JAVA |
The following MySQL creates a view that shows all Students learn 'JAVA':
CREATE VIEW javastudents AS
SELECT ROLL_NO, NAME,SUBJECT
FROM Students
WHERE SUBJECT = 'JAVA';
Now, you can query [javastudents] in a similar way as you query an actual table.
SELECT * FROM javastudents;
This would produce the following result.
ROLL_NO | NAME | SUBJECT |
---|---|---|
2 | SAM | JAVA |
4 | Rim | Java |
6 | Lara | JAVA |
A view always shows up-to-date data! The database engine recreates the data, using the view's MySQL statement, every time a user queries a view.