What is a VIEW in MySQL. How can you create and query a view?
What is a VIEW in MySQL. How can you create and query a view?
In MySQL, a VIEW is essentially a virtual table that is based on the result-set of an SQL statement. It contains rows and columns, just like a real table, but does not store data of its own. Instead, it displays data that is stored in other tables. This means that a VIEW allows you to create a selectable interface to the data that your SQL statement represents. It is particularly useful for encapsulating complex SQL queries, simplifying data access, and managing data security by restricting access to a predetermined set of rows and columns[1][2][6][11].
To create a VIEW in MySQL, you use the CREATE VIEW
statement followed by the view name and the SQL statement that defines the view. The basic syntax is as follows:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Here, view_name
is the name you want to give to your view, column1
, column2
, etc., are the columns you want to include in your view, table_name
is the name of the table where these columns are located, and condition
is any condition you want to apply to the rows included in your view[1][2][6][11].
Suppose you have a table named employees
with columns for id
, name
, department
, and salary
. You want to create a view that shows the name and department of all employees in the 'IT' department. The SQL statement to create this view would look like this:
CREATE VIEW it_employees AS
SELECT name, department
FROM employees
WHERE department = 'IT';
Once a VIEW is created, you can query it in the same way you would query a r...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào