Перейти к содержимому

Как создать представление в sql

  • автор:

Как создать представление в sql

Use the CREATE VIEW statement to define a view , which is a logical table based on one or more tables or views. A view contains no data itself. The tables upon which a view is based are called base tables .

You can also create an object view or a relational view that supports LOBs, object types, REF data types, nested table, or varray types on top of the existing view mechanism. An object view is a view of a user-defined type, where each row contains objects, each object with a unique object identifier.

You can also create XMLType views, which are similar to object views but display data from XMLSchema-based tables of XMLType .

Oracle XML DB Developer’s Guide for information on XMLType views

ALTER VIEW and DROP VIEW for information on modifying a view and removing a view from the database

To create a view in your own schema, you must have the CREATE VIEW system privilege. To create a view in another user’s schema, you must have the CREATE ANY VIEW system privilege.

To create a subview, you must have the UNDER ANY VIEW system privilege or the UNDER object privilege on the superview.

The owner of the schema containing the view must have the privileges necessary to either select ( READ or SELECT privilege), insert, update, or delete rows from all the tables or views on which the view is based. The owner must be granted these privileges directly, rather than through a role.

To use the basic constructor method of an object type when creating an object view, one of the following must be true:

The object type must belong to the same schema as the view to be created.

You must have the EXECUTE ANY TYPE system privileges.

You must have the EXECUTE object privilege on that object type.

SELECT, INSERT, UPDATE, and DELETE for information on the privileges required by the owner of a view on the base tables or views of the view being created

Specify OR REPLACE to re-create the view if it already exists. You can use this clause to change the definition of an existing view without dropping, re-creating, and regranting object privileges previously granted on it.

INSTEAD OF triggers defined on a conventional view are dropped when the view is re-created. DML triggers defined on an editioning view are retained when an editioning view is re-created. However, such triggers can be rendered permanently invalid if the editioning view has changed so that it can no longer be compiled—for example if an editioning view column referenced in the trigger definition has been dropped.

If any materialized views are dependent on view , then those materialized views will be marked UNUSABLE and will require a full refresh to restore them to a usable state. Invalid materialized views cannot be used by query rewrite and cannot be refreshed until they are recompiled.

You cannot replace a conventional view with an editioning view or an editioning view with a conventional view. See Oracle Database Development Guide for more information on editioning views.

ALTER MATERIALIZED VIEW for information on refreshing invalid materialized views

Oracle Database Concepts for information on materialized views in general

CREATE TRIGGER for more information about the INSTEAD OF clause

Specify FORCE if you want to create the view regardless of whether the base tables of the view or the referenced object types exist or the owner of the schema containing the view has privileges on them. These conditions must be true before any SELECT , INSERT , UPDATE , or DELETE statements can be issued against the view.

If the view definition contains any constraints, CREATE VIEW . FORCE fails if the base table does not exist or the referenced object type does not exist. CREATE VIEW . FORCE also fails if the view definition names a constraint that does not exist.

Specify NOFORCE if you want to create the view only if the base tables exist and the owner of the schema containing the view has privileges on them. This is the default.

Use this clause to create an editioning view . An editioning view is a single-table view that selects all rows from the base table and displays a subset of the base table columns. You can use an editioning view to isolate an application from DDL changes to the base table during administrative operations such as upgrades. You can obtain information about the relationship of existing editioning view to their base tables by querying the USER_ , ALL_ , and DBA_EDITIONING_VIEW data dictionary views.

The owner of an editioning view must be editions-enabled. Refer to ENABLE EDITIONS for more information.

Notes on Editioning Views

Editioning views differ from conventional views in several important ways:

Editioning views are intended only to select and provide aliases for a subset of columns in a table. Therefore, the syntax for creating an editioning view is more limited than the syntax for creating a conventional view. Any violation of the restrictions that follow causes the creation of the view to fail, even if you specify FORCE .

You can create DML triggers on editioning views. In this case, the database considers the editioning view to be the base object of the trigger. Such triggers fire when a DML operation target the editioning view itself. They do not fire if the DML operation targets the base table.

You cannot create INSTEAD OF triggers on editioning views.

Restrictions on Editioning Views

Editioning views are subject to the following restrictions:

Within any edition, you can create only one editioning view for any single table.

You cannot specify the object_view_clause , XMLType_view_clause , or BEQUEATH clause.

You cannot define a constraint WITH CHECK OPTION on an editioning view.

In the select list of the defining subquery, you can specify only simple references to the columns of the base table, and you can specify each column of the base table only once in the select list. The asterisk wildcard symbol * and t_alias . * are supported to designate all columns of a base table.

The FROM clause of the defining subquery of the view can reference only a single existing database table. Joins are not permitted. The base table must be in the same schema as the view being created. You cannot use a synonym to identify the table, but you can specify a table alias.

The following clauses of the defining subquery are not valid for editioning views: subquery_factoring_clause , DISTINCT or UNIQUE , where_clause , hierarchical_query_clause , group_by_clause , HAVING condition, model_clause , or the set operators ( UNION , INTERSECT , or MINUS )

Oracle Database Development Guide for detailed information about editioning views

CREATE EDITION for information about editions, including an example of an editioning view

Use these clauses to specify whether the view becomes an editioned or noneditioned object if editioning is enabled for the schema object type VIEW in schema . The default is EDITIONABLE . For information about editioned and noneditioned objects, see Oracle Database Development Guide .

Specify the schema to contain the view. If you omit schema , then Oracle Database creates the view in your own schema.

Specify the name of the view or the object view. The name must satisfy the requirements listed in «Database Object Naming Rules» .

Restriction on Views

If a view has INSTEAD OF triggers, then any views created on it must have INSTEAD OF triggers, even if the views are inherently updatable.

This clause applies only when creating a view in an application root. This type of view is called an application common object and its data can be shared with the application PDBs that belong to the application root. To determine how the view data is shared, specify one of the following sharing attributes:

METADATA — A metadata link shares the view’s metadata, but its data is unique to each container. This type of view is referred to as a metadata-linked application common object .

DATA — A data link shares the view, and its data is the same for all containers in the application container. Its data is stored only in the application root. This type of view is referred to as a data-linked application common object .

EXTENDED DATA — An extended data link shares the view, and its data in the application root is the same for all containers in the application container. However, each application PDB in the application container can store data that is unique to the application PDB. For this type of view, data is stored in the application root and, optionally, in each application PDB. This type of view is referred to as an extended data-linked application common object .

NONE — The view is not shared.

If you omit this clause, then the database uses the value of the DEFAULT_SHARING initialization parameter to determine the sharing attribute of the view. If the DEFAULT_SHARING initialization parameter does not have a value, then the default is METADATA .

When creating a conventional view, you can specify METADATA , DATA , EXTENDED DATA , or NONE .

When creating an object view or an XMLTYPE view, you can specify only METADATA or NONE .

You cannot change the sharing attribute of a view after it is created.

Oracle Database Reference for more information on the DEFAULT_SHARING initialization parameter

Oracle Database Administrator’s Guide for complete information on creating application common objects

Specify names for the expressions selected by the defining query of the view. The number of aliases must match the number of expressions selected by the view. Aliases must follow the rules for naming Oracle Database schema objects. Aliases must be unique within the view.

If you omit the aliases, then the database derives them from the columns or column aliases in the query. For this reason, you must use aliases if the query contains expressions rather than only column names. Also, you must specify aliases if the view definition includes constraints.

Restriction on View Aliases

You cannot specify an alias when creating an object view.

Use this clause to specify whether a view column is VISIBLE or INVISIBLE . By default, view columns are VISIBLE regardless of their visibility in the base tables, unless you specify INVISIBLE . This applies to conventional views and editioning views. For complete information on these clauses, refer to «VISIBLE | INVISIBLE» in the documentation on CREATE TABLE .

inline_constraint and out_of_line_constraint

You can specify constraints on views and object views. You define the constraint at the view level using the out_of_line_constraint clause. You define the constraint as part of column or attribute specification using the inline_constraint clause after the appropriate alias.

Oracle Database does not enforce view constraints. For a full discussion of view constraints, including restrictions, refer to «View Constraints» .

The object_view_clause lets you define a view on an object type.

OF type_name Clause

Use this clause to explicitly create an object view of type type_name . The columns of an object view correspond to the top-level attributes of type type_name . Each row will contain an object instance and each instance will be associated with an object identifier as specified in the WITH OBJECT IDENTIFIER clause. If you omit schema , then the database creates the object view in your own schema.

Object tables, as well as XMLType tables, object views, and XMLType views, do not have any column names specified for them. Therefore, Oracle Database defines a system-generated pseudocolumn OBJECT_ID . You can use this column name in queries and to create object views with the WITH OBJECT IDENTIFIER clause.

WITH OBJECT IDENTIFIER Clause

Use the WITH OBJECT IDENTIFIER clause to specify a top-level (root) object view. This clause lets you specify the attributes of the object type that will be used as a key to identify each row in the object view. In most cases these attributes correspond to the primary key columns of the base table. You must ensure that the attribute list is unique and identifies exactly one row in the view. The WITH OBJECT IDENTIFIER and WITH OBJECT ID clauses can be used interchangeably and are provided for semantic clarity.

Restrictions on Object Views

Object views are subject to the following restrictions:

If you try to dereference or pin a primary key REF that resolves to more than one instance in the object view, then the database returns an error.

You cannot specify this clause if you are creating a subview, because subviews inherit object identifiers from superviews.

If the object view is defined on an object table or an object view, then you can omit this clause or specify DEFAULT .

Specify DEFAULT if you want the database to use the intrinsic object identifier of the underlying object table or object view to uniquely identify each row.

For attribute , specify an attribute of the object type from which the database should create the object identifier for the object view.

Use the UNDER clause to specify a subview based on an object superview.

Restrictions on Subviews

Subviews are subject to the following restrictions:

You must create a subview in the same schema as the superview.

The object type type_name must be the immediate subtype of superview .

You can create only one subview of a particular type under the same superview.

CREATE TYPE for information about creating objects

Oracle Database Reference for information on data dictionary views

Use this clause to create an XMLType view, which displays data from an XMLSchema-based table of type XMLType . The XMLSchema_spec indicates the XMLSchema to be used to map the XML data to its object-relational equivalents. The XMLSchema must already have been created before you can create an XMLType view.

The WITH OBJECT IDENTIFIER and WITH OBJECT ID clauses can be used interchangeably and are provided for semantic clarity.

Object tables, as well as XMLType tables, object views, and XMLType views, do not have any column names specified for them. Therefore, Oracle Database defines a system-generated pseudocolumn OBJECT_ID . You can use this column name in queries and to create object views with the WITH OBJECT IDENTIFIER clause.

Oracle XML DB Developer’s Guide for information on XMLType views and XMLSchemas

Use this clause to specify the default collation for the view. The default collation is used as the derived collation for all the character literals included in the defining query of the view. The default collation is not used by the view columns; the collations for the view columns are derived from the view’s defining subquery. The CREATE VIEW statement fails with an error if any of its character columns is based on an expression in the defining subquery that has no derived collation.

For collation_name , specify a valid named collation or pseudo-collation.

If you omit this clause, then the default collation for the view is set to the effective schema default collation of the schema containing the view. Refer to the DEFAULT_COLLATION clause of ALTER SESSION for more information on the effective schema default collation.

You can specify the DEFAULT COLLATION clause only if the COMPATIBLE initialization parameter is set to 12.2 or greater, and the MAX_STRING_SIZE initialization parameter is set to EXTENDED .

To change the default collation for a view, you must recreate the view.

Restriction on the Default Collation for Views

If the defining query of the view contains the WITH plsql_declarations clause, then the default collation of the view must be USING_NLS_COMP .

Use the BEQUEATH clause to specify whether functions referenced in the view are executed using the view invoker’s rights or the view definer’s rights.

If you specify BEQUEATH CURRENT_USER , then functions referenced by the view are executed using the view invoker’s rights as long as one of the following conditions is met:

The view owner has the INHERIT PRIVILEGES object privilege on the invoking user.

The view owner has the INHERIT ANY PRIVILEGES system privilege.

If a query of the view invokes an identity- or privilege-sensitive SQL function, or an invoker’s rights PL/SQL or Java function, then the current schema, current user, and currently enabled roles within the operation’s execution are inherited from the querying user’s environment, rather than from the owner of the view.

This clause does not turn the view itself into an invoker’s rights object. Name resolution within the view is still handled using the view owner’s schema, and privilege checking for the view is done using the view owner’s privileges.

If you specify BEQUEATH DEFINER , then functions referenced by the view are executed using the view definer’s rights. If a query on the view invokes an identity- or privilege-sensitive SQL function, or an invoker’s rights PL/SQL or Java function, then the current schema, current user, and currently enabled roles within the operation’s execution are inherited from the owner of the view.

Name resolution within the view is handled using the view owner’s schema, and privilege checking for the view is done using the view owner’s privileges.

This is the default.

Restriction on the BEQUEATH Clause

You cannot specify this clause with the EDITIONING clause.

Oracle Database Security Guide for more information on controlling invoker’s rights and definer’s rights in views

Specify a subquery that identifies columns and rows of the table(s) that the view is based on. The select list of the subquery can contain up to 1000 expressions.

If you create views that refer to remote tables and views, then the database links you specify must have been created using the CONNECT TO clause of the CREATE DATABASE LINK statement, and you must qualify them with a schema name in the view subquery.

If you create a view with the flashback_query_clause in the defining query, then the database does not interpret the AS OF expression at create time but rather each time a user subsequently queries the view.

Restrictions on the Defining Query of a View

The view query is subject to the following restrictions:

The subquery cannot select the CURRVAL or NEXTVAL pseudocolumns.

If the subquery selects the ROWID , ROWNUM , or LEVEL pseudocolumns, then those columns must have aliases in the view subquery.

If the subquery uses an asterisk (*) to select all columns of a table, and you later add new columns to the table, then the view will not contain those columns until you re-create the view by issuing a CREATE OR REPLACE VIEW statement.

For object views, the number of elements in the subquery select list must be the same as the number of top-level attributes for the object type. The data type of each of the selecting elements must be the same as the corresponding top-level attribute.

You cannot specify the SAMPLE clause.

The preceding restrictions apply to materialized views as well.

Notes on Updatable Views

The following notes apply to updatable views:

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.

The view must not contain any of the following constructs:

  • A set operator
  • A DISTINCT operator
  • An aggregate or analytic function
  • A GROUP BY , ORDER BY , MODEL , CONNECT BY , or START WITH clause
  • A collection expression in a SELECT list
  • A subquery in a SELECT list
  • A subquery designated WITH READ ONLY
  • Joins, with some exceptions, as documented in Oracle Database Administrator’s Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

The DML statement must affect only one table underlying the join.

For an INSERT statement, the view must not be created WITH CHECK OPTION , and all columns into which values are inserted must come from a key-preserved table . A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.

For an UPDATE statement, the view must not be created WITH CHECK OPTION , and all columns updated must be extracted from a key-preserved table.

For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION .

Oracle Database Administrator’s Guide for more information on updatable views

«Creating an Updatable View: Example» , «Creating a Join View: Example» for an example of updatable join views and key-preserved tables, and Oracle Database PL/SQL Language Reference for an example of an INSTEAD OF trigger on a view that is not inherently updatable

Use the subquery_restriction_clause to restrict the defining query of the view in one of the following ways:

Specify WITH READ ONLY to indicate that the table or view cannot be updated.

WITH CHECK OPTION

Specify WITH CHECK OPTION to indicate that Oracle Database prohibits any changes to the table or view that would produce rows that are not included in the subquery. When used in the subquery of a DML statement, you can specify this clause in a subquery in the FROM clause but not in subquery in the WHERE clause.

Specify the name of the READ ONLY or CHECK OPTION constraint. If you omit this identifier, then Oracle automatically assigns the constraint a name of the form SYS_C n , where n is an integer that makes the constraint name unique within the database.

For tables, WITH CHECK OPTION guarantees that inserts and updates result in tables that the defining table subquery can select. For views, WITH CHECK OPTION cannot make this guarantee if:

There is a subquery within the defining query of this view or any view on which this view is based or

INSERT , UPDATE , or DELETE operations are performed using INSTEAD OF triggers.

Restriction on the subquery_restriction_clause

You cannot specify this clause if you specify an ORDER BY clause.

Specify the CONTAINER_MAP clause to enable the view to be queried using a container map.

Specify the CONTAINERS_DEFAULT clause to enable the view for the CONTAINERS clause.

Creating a View: Example

The following statement creates a view of the sample table employees named emp_view . The view shows the employees in department 20 and their annual salary:

The view declaration need not define a name for the column based on the expression salary*12 , because the subquery uses a column alias ( annual_salary ) for this expression.

Creating an Editioning View: Example

The following statement creates an editioning view of the orders table:

You can use this view to isolate an application from DDL changes to the orders table during an administrative operation such as an upgrade. You can create a DML trigger on this view, so that the trigger fires when a DML operation targets the view itself, but does not fire if the DML operation targets the orders table.

Creating a View with Constraints: Example

The following statement creates a restricted view of the sample table hr.employees and defines a unique constraint on the email view column and a primary key constraint for the view on the emp_id view column:

Creating an Updatable View: Example

The following statement creates an updatable view named clerk of all clerks in the employees table. Only the employees’ IDs, last names, department numbers, and jobs are visible in this view, and these columns can be updated only in rows where the employee is a kind of clerk:

This view lets you change the job_id of a purchasing clerk to purchasing manager ( PU_MAN ):

The next example creates the same view WITH CHECK OPTION . You cannot subsequently insert a new row into clerk if the new employee is not a clerk. You can update an employee’s job_id from one type of clerk to another type of clerk, but the update in the preceding statement would fail, because the view cannot access employees with non-clerk job_id .

Creating a Join View: Example

A join view is one whose view subquery contains a join. If at least one column in the join has a unique index, then it may be possible to modify one base table in a join view. You can query USER_UPDATABLE_COLUMNS to see whether the columns in a join view are updatable. For example:

In the preceding example, the primary key index on the location_id column of the locations table is not unique in the locations_view view. Therefore, locations is not a key-preserved table and columns from that base table are not updatable.

You can insert, update, or delete a row from the departments base table, because all the columns in the view mapping to the departments table are marked as updatable and because the primary key of departments is retained in the view.

For you to insert into the table using the view, the view must contain all NOT NULL columns of all tables in the join, unless you have specified DEFAULT values for the NOT NULL columns.

Oracle Database Administrator’s Guide for more information on updating join views

Creating a Read-Only View: Example

The following statement creates a read-only view named customer_ro of the oe.customers table. Only the customers’ last names, language, and credit limit are visible in this view:

Creating an Object View: Example

The following example shows the creation of the type inventory_typ in the oc schema, and the oc_inventories view that is based on that type:

Creating a View on an XMLType Table: Example

The following example builds a regular view on the XMLType table xwarehouses , which was created in «Examples» :

SQL — Использование представлений

SQL — Использование представлений

От автора: представление — это не что иное, как оператор SQL, который хранится в базе данных с соответствующим именем. На самом деле представление является определенным структурированным набором данных таблицы в виде предопределенного SQL-запроса.

Представления SQL могут содержать все строки таблицы или определенные выбранные строки. Представление может быть создано из одной или нескольких таблиц, это зависит от составленного для представления SQL-запроса.

Представления, которые являются типом виртуальных таблиц, позволяют пользователям делать следующее:

Структурировать данные таким образом, который будет наиболее естественным или интуитивным для пользователей или классов пользователей.

Ограничивать доступ к данным таким образом, чтобы пользователь мог находить и изменять (в некоторых случаях) только те данные, которые ему нужны, и не более того.

Обобщать данные из разных таблиц, чтобы использовать их для различных отчетов.

Создание представлений

Представления базы данных создаются с помощью инструкции CREATE VIEW. Представления можно создать из одной таблицы, нескольких таблиц или другого представления.

Пользователь должен иметь соответствующие системные привилегии в зависимости от конкретной реализации.
Основной синтаксис CREATE VIEW следующий:

Представление (VIEW) в SQL

В SQL представления (views) содержат строки и столбцы, аналогичные таблицам, однако без фактических данных. Представление можно рассматривать как виртуальную таблицу, созданную из одной или нескольких таблиц, чтобы упростить работу с данными.

Создание представления в SQL

Мы можем создавать представления в SQL с помощью команды CREATE VIEW. Например:

Здесь представление с именем us_customers создается из таблицы Customers. Теперь, чтобы выбрать клиентов, которые живут в USA , мы можем просто написать:

Обновление представления

Можно изменить или обновить существующее представление с помощью команды CREATE OR REPLACE VIEW. Например:

Здесь мы обновили представление us_customers для того, чтобы получить все поля таблицы Customers.

Удаление представления

Мы можем удалить представление с помощью команды DROP VIEW. Например:

Здесь мы удаляем представление с именем us_customers.

Примечание: Если представление на момент выполнения команды удаления не существует, то SQL выдаст ошибку.

Представления для сложных запросов

Предположим, что A и B — это две таблицы, с которых мы хотим получить данные. Для этого мы можем использовать операторы JOIN. Однако использование JOIN каждый раз может быть утомительной задачей. В качестве альтернативы можно создать представление для простого извлечения данных.

Представления в SQL

Здравствуйте, в этой статье будут разобраны представления или view в SQL. На простых примерах объясним как создавать представления и как к ним обращаться. Также затронем понятие модифицируемого представления в SQL.

Общее понятие

Итак, представления в SQL являются особым объектом, который содержит данные, полученные запросом SELECT из обычных таблиц. Это виртуальная таблица, к которой можно обратиться как к обычным таблицам и получить хранимые данные. Представление в SQL может содержать в себе как данные из одной единственной таблицы, так и из нескольких таблиц.

Представления нужны для того, чтобы упростить работу с базой данных и ускорить время ответа сервера. Так как представление — это уже результат некой выборки данных с помощью SELECT, то, очевидно, в следующий раз вместо запроса к нескольким таблицам достаточно просто обратиться к уже созданному представлению. Работу этого объекта характеризует следующее изображение:

На изображении — простой вариант использования представления, когда объединяются данные по идентификатору. Но, помимо этого, в представлениях могут быть разные виды условий и ограничений, также вложенные запросы и группировки по каким либо полям. Об этом будет сказано чуть позже.

Создание представления в SQL

Создание представления осуществляется следующей командой:

Где name_view — имя, которое задает пользователь при создании. После ключевого слова as идет код запроса SELECT, данные которого и поместятся в представление. Чтобы легче понять разберем простой пример, иллюстрация которого была представлена выше.

С помощью SELECT выбираются данные и помещаются в представление. Еще раз повторим, что когда данные в исходных таблицах изменятся, то они поменяются и в представлении.

Теперь представление практически является таблицей, если вы используете phpmyadmin, то слева в меню можно увидеть такую картину:

Обращение к представлениям в SQL

Чтобы посмотреть данные из представления следует воспользоваться теми командами, которые были изучены в предыдущих уроках — например по оператору SELECT в SQL.

Помимо простого SELECT, в SQL к представлениям можно обращаться с различными условиями WHERE, как к обычным таблицам. Также можно использовать данные из этого представления, чтобы сформировать новое представление — хотя это и редко используется, тем не менее, в SQL есть такая возможность.

Примеры представлений

Пока что были рассмотрены самые простые примеры на представления. В целом, следующие примеры также не будут слишком сложными, если были изучены предыдущие статьи, но все равно необходимо познакомиться с возможными применениями.

Рассмотрим такую задачу:

Создайте представление Cust_Rating_Max, которое бы показывало всех покупателей и их город, которые имеют самые высокие рейтинги.

Хорошей практикой является решение задачи запроса SELECT, а затем уже создание самого представления. То есть сначала лучше написать запрос, который вернет на экран то, что нужно. Затем создать представление. Вот итоговый код решения этой задачи:

Теперь это представление может использоваться как обычная таблица, но преимущество в том, что данные изменяются автоматически при добавлении или изменении данных в основных таблицах.

Создайте представление Sale_Amt_Avg, которое бы показывало усредненные суммы заказов для каждого продавца после его имени.

Нужно сделать группировку по имени продавца и следующий код нам в этом поможет:

По сути для каждого продавца рассчитывается среднее значение сумм его продаж и заносится в представление.

Это выделено в отдельный пункт, так как не все СУБД SQL поддерживают представления с сортировкой, но мы рассмотрим такую задачу:

Создайте представление Orders_All, которое бы показывало данные о заказах: сумму, дату, фамилию покупателя и продавца. Отсортировать по сумме заказа.

В этом запросе по сути создается представление, которое дублирует таблицу orders, и заменяет в ней идентификаторы на фамилии. Также происходит сортировка по сумме заказа.

На этом с практикой мы закончим и еще немного поговорим о теории представлений.

Понятие модифицируемого представления в SQL

Итак, в SQL есть такое понятие как модифицируемого представление — это означает, что при изменении данных в самом представлении, эти данные изменятся и в таблицах, которые эти данные хранят. То есть при использовании оператора UPDATE/INSERT/DELETE к представлению, данные обновятся и в таблицах.

Очевидно, что не все представления являются такими и на самом деле большая часть является немодифицируемыми. По причине неоднозначности: например в представлении хранятся данные из двух таблиц. Пользователь удаляет одну строку в представлении, и тут возникает вопрос — удалять ли исходные данные в таблицах, а если и удалять, то сразу из двух или только одной… В этом и состоит неоднозначность.

Поэтому выделили специальные критерии по которым можно определенно сказать — является ли представление SQL модифицируемым. Эти критерии вы можете найти по этой ссылке — тут статья на очень полезном ресурсе по SQL языку.

Заключение

На этом все для представлений. В этой статье было много теории, но без этого сложно понять как работают представления в SQL. Если у вас остались вопросы — задавайте их в комментариях и по возможности делитесь данными уроками в социальных сетях.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *