I would like to know what is the CREATE VIEW
command for MySQL?
I would like to know what is the CREATE VIEW
command for MySQL?
CREATE VIEW
creates an object of type VIEW
in its database.
A View is a transformation on top of one or more tables that behaves like a table. It is usually read-only (you can not insert, change, or delete lines from it).
Example:
CREATE VIEW MinhaView AS
SELECT COLUNA2, COLUNA4, COLUNA6
FROM TABELA
WHERE COLUNA1 = 1;
You can select data directly over View after creation:
SELECT * FROM MinhaView;
The result will be equivalent to the SELECT
that is part of the View body.
EDIT
Example asked for comment:
CREATE VIEW MinhaView2 AS
SELECT CONCAT(NOME, ' ', SOBRENOME) AS NOME_COMPLETO, COLUNA2, COLUNA3, COLUNA4
FROM TABELA_COM_NOME;
Serves to create a 'read-only table' / virtual table that is based on queries. It can work as a shortcut for long queries.
Instead of putting this query in multiple places in the code
SELECT p.nome, c.categoria_descricao, t.tipo_descricao FROM produtos as p
INNER JOIN categorias as c ON p.id_categoria = c.id_categoria
INNER JOIN tipo as t ON p.id_tipo = t.id_tipo
You could create a view to bring the description and product type, simplifying your call.
CREATE view produto_simplificado as
SELECT p.nome, c.categoria_descricao, t.tipo_descricao FROM produtos as p
INNER JOIN categorias as c ON p.id_categoria = c.id_categoria
INNER JOIN tipo as t ON p.id_tipo = t.id_tipo
then you would just call it that way
SELECT * FROM produto_simplificado
A quote taken from the IMaster post ( Working with VIEWS in MYSQL )
A View is an object that belongs to a database, defined based on SELECT statements, returning a certain data from one or more tables. These objects are sometimes referred to as "virtual tables", formed from other tables that are called "based tables" or Views. And in some cases, Views are upgradeable and can be statement INSERT, UPDATE, and DELETE, which actually modify your "Based tables".
The benefits of using Views, in addition to those already highlighted, are:
A View can be used, for example, to return a value based on a record identifier; It can be used to promote restrictions on data to increase data security and define table-level and column-level access policies. Can be configured to display different columns for different users the database; It can be used with a set of tables that can be joined to other sets of tables with the use of JOIN's or UNION.
A View is a SELECT query that gets saved in the database for later use. When you need View data in any context, just use the View's name, which will be as a sub-SELECT at the point where the View name is used.