Довідка LibreOfficeDev 25.8
Конструктор запитів дозволяє створити або змінити запит до бази даних.
Більшість баз даних використовують для фільтрування або сортування таблиць баз даних для відображення записів на вашому комп’ютері запити. Подання пропонують ту ж функціональність, що й запити, але на боці сервера. Якщо ваша база даних розташована на сервері, який підтримує подання, ви можете використовувати подання для фільтрування записів на сервері, щоб прискорити показ.
Вибравши команду Створити подання на вкладці Таблиці документа бази даних, ви побачите вікно Дизайн подання, яке нагадує описаний тут Конструктор запитів.
Макет вікна "Конструктор запитів" зберігається зі створеним запитом, але не може зберігатися зі створеним поданням.
Щоб створити запит, клацніть у документі бази даних піктограму Запити, а потім натисніть Створити запит у конструкторі.
The lower pane of the Design View is where you define the query. To define a query, specify the database field names to include and the criteria for displaying the fields. To rearrange the columns in the lower pane of the Design View, drag a column header to a new location, or select the column and press +arrow key.
У верхній частині вікна "Конструктор запиту" є піктограми панелей Конструктор запитів і Дизайн.
Щоб перевірити запит, двічі клацніть його назву в документі бази даних. Результат запиту виводиться у таблиці, подібній до подання джерела даних. Примітка: виведена таблиця є тимчасовою.
| Клавіша | Дія | 
|---|---|
| F4 | Попередній перегляд | 
| F5 | Запустити запит | 
| F7 | Додати таблицю або запит | 
При першому відкритті конструктора запиту, виводиться діалогове вікно, у якому потрібно вибрати таблицю або запит, які стануть основою для нового запиту.
Двічі клацніть поля, щоб додати їх до запиту. Перетягніть, щоб визначити відношення.
Під час розробки запиту не можна змінювати вибрані таблиці.
Щоб вилучити таблицю з конструктора, клацніть верхню межу вікна таблиці та відкрийте контекстне меню і скористайтесь командою Видалити. Також можна натиснути клавішу Delete.
Ви можете змінити розмір та розташувати таблиці відповідно до ваших уподобань. Щоб перемістити таблиці, перетягніть верхню межу до потрібного положення. Збільшіть або зменшіть розмір відображення таблиці, перетягнувши її межу або куток.
Якщо між назвами полів таблиць є відношення даних, ви можете їх використовувати в запиті.
Якщо, наприклад, є електронна таблиця статей, ідентифікована номером статті, та електронна таблиця клієнтів, у якій ви записуєте всі статті, які замовляє клієнт, використовуючи відповідні номери статей, то між двома полями даних "номер статті" існує зв'язок. Якщо потрібно створити запит, який повертає всі статті, які замовив клієнт, ви маєте отримати дані з двох електронних таблиць. Для цього слід повідомити LibreOfficeDev про зв'язок, який існує між даними цих таблиць.
Для цього клацніть назву поля в таблиці (наприклад, назву "Номер-елемента" в таблиці "Клієнт"), натисніть кнопку миші, а потім перетягніть назву поля на назву поля іншої таблиці ("Номер-елемента" з таблиці Елемент). Коли ви відпустите кнопку миші, між двома вікнами з'явиться лінія, що з'єднує два поля таблиць. Відповідна умова про те, що вміст двох полів має збігатись, уводиться в кінцевий запит SQL.
Створення запиту на основі кількох пов'язаних аркушів можливе лише за умови використання LibreOfficeDev як інтерфейсу для реляційної бази даних.
Ви не можете в запиті отримати доступ до таблиць із різних баз даних. Запити з кількома таблицями можна створювати лише в одній базі даних.
Якщо двічі клацнути лінію, що з'єднує два пов'язаних поля, або викликати команду меню Вставка - Створити зв'язок, можна в діалоговому вікні Зв'язки задати тип зв'язку.
Можна також натискати Tab, поки лінія стане вибраною, потім натиснути Shift+F10, щоб побачити контекстне меню, а в ньому вибрати команду Змінити. Деякі бази даних підтримують лише частину можливих типів об’єднання.
Щоб видалити зв’язок між двома таблицями, клацніть лінію з’єднання, а потім натисніть клавішу Delete.
Також можна видалити відповідні записи зі списку Включені поля в діалоговому вікні Зв'язки. Або натискати Tab, поки з'єднувальна лінія стане вибраною, потім натиснути Shift+F10, щоб побачити контекстне меню, і вибрати команду Видалити.
Виберіть умови для визначення запиту. Кожен стовпець таблиці проєктування містить поле даних для запиту. Умови в одному рядку пов’язані логічним І.
Спочатку виберіть усі назви полів із таблиць, які потрібно додати до запиту. Ви можете зробити це перетягуванням або подвійним клацанням назви поля у вікні таблиці. За допомогою миші перетягніть ім'я поля з вікна таблиці в нижню область вікна формування запиту. Таким чином Ви можете вирішити, який стовпець у вікні формування запиту отримає вибране поле. Назву поля також можна вибрати подвійним клацанням. Потім воно буде додано до наступного вільного стовпця у вікні формування запиту.
Щоб видалити назву поля із запиту, клацніть заголовок стовпця поля та виберіть у контекстному меню команду Видалити.
Щоб зберегти запит, натисніть піктограму Зберегти на панелі Стандартна. Ви побачите діалогове вікно з проханням увести назву запиту. Якщо база даних підтримує схеми, ви також можете ввести назву схеми.
Введіть назву схеми, призначеної для запиту або табличного подання.
Введіть назву запиту або табличного подання.
Щоб відфільтрувати дані для запиту, встановіть бажані критерії в нижній частині вікна формування запиту. Доступні такі варіанти:
Введіть назву поля даних, на яке посилається запит. Усі налаштування, зроблені в рядках параметрів фільтра, стосуються цього поля. Якщо активувати цю комірку клацанням миші, з'явиться кнопка зі стрілкою, яка дозволяє вибрати поле. Параметр «Назва таблиці.*» вибирає всі поля даних з ефектом, що задані критерії будуть застосовані до всіх полів таблиці.
Задає псевдонім. Цей псевдонім буде вказано в запиті замість назви поля. Це дозволяє використовувати визначені користувачем мітки стовпців. Наприклад, якщо поле даних має назву PtNo і замість неї ви хочете, щоб у запиті відображалося PartNum, уведіть PartNum як псевдонім.
У операторі SQL псевдоніми визначаються так:
SELECT стовпець AS псевдонім FROM таблиця.
Наприклад:
SELECT "PtNo" AS "PartNum" FROM "Parts"
Тут вказано таблицю бази даних відповідну вибраному полю даних. Якщо клацнути цю комірку, з’явиться стрілка, яка дозволить вибрати для поточного запиту іншу таблицю.
Якщо натиснути на цю комірку, можна вибрати варіант сортування: за зростанням, за спаданням і без сортування. Текстові поля будуть відсортовані за алфавітом, а числові – за числовим значенням. Для більшості баз даних адміністратори можуть встановлювати параметри сортування на рівні бази даних.
Якщо для поля даних встановити властивість Видиме, це поле буде показано в результаті запиту. Якщо поле даних потрібне лише для формулювання умови або обчислення, його не обов’язково робити видимим.
Specifies a first criteria by which the content of the data field is to be filtered.
Тут можна ввести один додатковий критерій фільтрації для кожного рядка. Кілька критеріїв в одному стовпці будуть пов'язані логічним АБО.
Ви також можете використати контекстне меню заголовків рядків у нижній частині вікна формування запиту, щоб встановити фільтр на основі функції:
Доступні тут функції залежать від функцій, наданих СУБД.
If you are working with the embedded HSQL database, the list box in the Function row offers you the following options:
| Option | SQL | Effect | 
|---|---|---|
| No function | No function will be executed. | |
| Average | AVG | Calculates the arithmetic mean of a field. | 
| Count | COUNT | Determines the number of records in the table. Empty fields can either be counted (a) or excluded (b). a) COUNT(*): Passing an asterisk as the argument counts all records in the table. b) COUNT(column): Passing a field name as an argument counts only the records in which the specified field contains a value. Records in which the field has a Null value (i.e. contains no textual or numeric value) will not be counted. | 
| Maximum | MAX | Determines the highest value of a record for that field. | 
| Minimum | MIN | Determines the lowest value of a record for that field. | 
| Sum | SUM | Calculates the sum of the values of records for the associated fields. | 
| Group | GROUP BY | Groups query data according to the selected field name. Functions are executed according to the specified groups. In SQL, this option corresponds to the GROUP BY clause. If a criterion is added, this entry appears in the SQL HAVING sub-clause. | 
You can also enter function calls directly into the SQL statement. The syntax is:
SELECT FUNCTION(column) FROM table.
For example, the function call in SQL for calculating a sum is:
SELECT SUM("Price") FROM "Article".
Except for the Group function, the above functions are called Aggregate functions. These are functions that calculate data to create summaries from the results. Additional functions that are not listed in the list box might be also possible. These depend on the specific database engine in use and on the current functionality provided by the Base driver used to connect to that database engine.
To use other functions not listed in the list box, you must enter them manually under Field.
You can also assign aliases to function calls. If you do not want to display the query string in the column header, enter a desired substitute name under Alias.
The corresponding function in an SQL statement is:
SELECT FUNCTION() AS alias FROM table
Example:
SELECT COUNT(*) AS count FROM "Item"
If you run such a function, you cannot insert any additional columns for the query other than as an argument in a "Group" function.
Examples
In the following example, a query is run through two tables: an "Item" table with the "Item_No" field and a "Suppliers" table with the "Supplier_Name" field. In addition, both tables have a common field name "Supplier_No."
The following steps are required to create a query containing all suppliers who deliver more than three items.
Insert the "Item" and "Suppliers" tables into the query design.
Link the "Supplier_No" fields of the two tables if there is not already a relation of this type.
Double-click on the "Item_No" field from the "Item" table. Display the Function line using the context menu and select the Count function.
Enter >3 as a criterion and disable the Visible field.
Double-click the "Supplier_Name" field in the "Suppliers" table and choose the Group function.
Run the query.
If the "price" (for the individual price of an article) and "Supplier_No" (for the supplier of the article) fields exist in the "Item" table, you can obtain the average price of the item that a supplier provides with the following query:
Insert the "Item" table into the query design.
Double-click the "Price" and "Supplier_No" fields.
Enable the Function line and select the Average function from the "Price" field.
You can also enter "Average" in the line for the alias name (without quotation marks).
Choose Group for the "Supplier_No" field.
Run the query.
The following context menu commands and symbols are available:
Shows or hides a row for the selection of functions.
Shows or hides the row for the table name.
Shows or hides the row for the alias name.
Retrieves only distinct values from the query. This applies to multiple records that might contain several repeating occurrences of data in the selected fields. If the Distinct Values command is active, you should only see one record in the query (DISTINCT). Otherwise, you will see all records corresponding to the query criteria (ALL).
For example, if the name "Smith" occurs several times in your address database, you can choose the Distinct Values command to specify in the query that the name "Smith" will occur only once.
For a query involving several fields, the combination of values from all fields must be unique so that the result can be formed from a specific record. For example, you have "Smith in Chicago" once in your address book and "Smith in London" twice. With the Distinct Values command, the query will use the two fields "last name" and "city" and return the query result "Smith in Chicago" once and "Smith in London" once.
In SQL, this command corresponds to the DISTINCT predicate.
Allows you to limit the maximum number of records returned by a query.
If a Limit construction is added, you will get at most as many rows as the number you specify. Otherwise, you will see all records corresponding to the query criteria.
When formulating filter conditions, various operators and commands are available to you. Apart from the relational operators, there are SQL-specific commands that query the content of database fields. If you use these commands in the LibreOfficeDev syntax, LibreOfficeDev automatically converts these into the corresponding SQL syntax via an internal parser. You can also enter the SQL command directly and bypass the internal parser. The following tables give an overview of the operators and commands:
| Operator | Meaning | Condition is satisfied if... | 
|---|---|---|
| = | equal to | ... the content of the field is identical to the indicated expression. The operator = will not be displayed in the query fields. If you enter a value without any operator, the = operator is automatically assumed. | 
| <> | not equal to | ... the content of the field does not correspond to the specified expression. | 
| > | greater than | ... the content of the field is greater than the specified expression. | 
| < | less than | ... the content of the field is less than the specified expression. | 
| >= | greater than or equal to | ... the content of the field is greater than or equal to the specified expression. | 
| <= | less than or equal to | ... the content of the field is less than or equal to the specified expression. | 
| ='Ms.' | returns field names with the field content "Ms." | 
| <'2001-01-10' | returns dates that occurred before January 10, 2001 | 
| LIKE 'g?ve' | returns records with field content such as "give" and "gave". | 
| LIKE 'S*' | returns records with field contents such as "Sun". | 
| BETWEEN 10 AND 20 | returns records with field content between the values 10 and 20. (The fields can be either text fields or number fields). | 
| IN (1; 3; 5; 7) | returns records with the values 1, 3, 5, 7. If the field name contains an item number, for example, you can create a query that returns the item having the specified number. | 
| NOT IN ('Smith') | returns records that do not contain "Smith". | 
Like Escape Sequence: {escape 'escape-character'}
SELECT * FROM Item WHERE ItemName LIKE 'The *%' {escape '*'}
The example will give you all of the entries where the item name begins with 'The *'. This means that you can also search for characters that would otherwise be interpreted as placeholders, such as *, ?, _, % or the period.
Outer Join Escape Sequence: {oj outer-join}
SELECT Article.* FROM {oj item LEFT OUTER JOIN orders ON item.no=orders.ANR}
To query the content of a text field, you must put the expression between single quotes. The distinction between uppercase and lowercase letters depends on the database in use. LIKE, by definition, is case-sensitive (though some databases don't interpret this strictly).
Date fields are represented as #Date# to clearly identify them as dates. Date, time and date/time constants (literals) used in conditions can be of either the SQL Escape Syntax type, or default SQL2 syntax.
| Date Type Element | SQL Escape syntax #1 - may be obsolete | SQL Escape syntax #2 | SQL2 syntax | 
|---|---|---|---|
| Date | {D'YYYY-MM-DD'} | {d 'YYYY-MM-DD'} | 'YYYY-MM-DD' | 
| Time | {D'HH:MM:SS'} | {t 'HH:MI:SS[.SS]'} | 'HH:MI:SS[.SS]' | 
| DateTime | {D'YYYY-MM-DD HH:MM:SS'} | {ts 'YYYY-MM-DD HH:MI:SS[.SS]'} | 'YYYY-MM-DD HH:MI:SS[.SS]' | 
SELECT {d '1999-12-31'} FROM world.years
SELECT * FROM mytable WHERE years='1999-12-31'
All date expressions (date literals) must be enclosed with single quotation marks. (Consult the reference for the particular database and connector you are using for more details.)
To query Yes/No fields, use the following syntax for dBASE tables:
| Status | Query criterion | Example | 
|---|---|---|
| Yes | for dBASE tables: not equal to any given value | =1 returns all records where the Yes/No field has the status "Yes" or "On" (selected in black), | 
| No | . | =0 returns all records for which the Yes/No field has the status "No" or "Off" (no selection). | 
| Null | IS NULL | IS NULL returns all records for which the Yes/No field has neither of the states Yes or No (selected in gray). | 
The syntax depends on the database system used. You should also note that Yes/No fields can be defined differently (only 2 states instead of 3).
Parameter queries allow the user to input values at run-time. These values are used within the criteria for selecting the records to be displayed. Each such value has a parameter name associated with it, which is used to prompt the user when the query is run.
Parameter names are preceded by a colon in both the Design and SQL views of a query. This can be used wherever a value can appear. If the same value is to appear more than once in the query, the same parameter name is used.
In the simplest case, where the user enters a value which is matched for equality, the parameter name with its preceding colon is simply entered in the Criterion row. In SQL mode this should be typed as WHERE "Field" = :Parameter_name
Parameter names may not contain any of the characters <space>`!"$%^*()+={}[]@'~#<>?/,. They may not be the same as field names or SQL reserved words. They may be the same as aliases.
A useful construction for selecting records based on parts of a text field's content is to add a hidden column with "LIKE '%' || :Part_of_field || '%'" as the criterion. This will select records with an exact match. If a case-insensitive test is wanted, one solution is to use LOWER (Field_Name) as the field and LIKE LOWER ( '%' || :Part_of_field || '%' ) as the criterion. Note that the spaces in the criterion are important; if they are left out the SQL parser interprets the entire criterion as a string to be matched. In SQL mode this should be typed as LOWER ( "Field_Name" ) LIKE LOWER ( '%' || :Part_of_field || '%' ).
Parameter queries may be used as the data source for subforms, to allow the user to restrict the displayed records.
The Parameter Input dialog asks the user to enter the parameter values. Enter a value for each query parameter and confirm by clicking OK or typing Enter.
The values entered by the user may consist of any characters which are allowable for the SQL for the relevant criterion; this may depend on the underlying database system.
The user can use the SQL wild-card characters "%" (arbitrary string) or "_" (arbitrary single character) as part of the value to retrieve records with more complex criteria.
SQL stands for "Structured Query Language" and describes instructions for updating and administering relational databases.
In LibreOfficeDev you do not need any knowledge of SQL for most queries, since you do not have to enter the SQL code. If you create a query in the query designer, LibreOfficeDev automatically converts your instructions into the corresponding SQL syntax. If, with the help of the Switch Design View On/Off button, you change to the SQL view, you can see the SQL commands for a query that has already been created.
You can formulate your query directly in SQL code. Note, however, that the special syntax is dependent upon the database system that you use.
If you enter the SQL code manually, you can create SQL-specific queries that are not supported by the graphical interface in the Query designer. These queries must be executed in native SQL mode.
By clicking the Run SQL command directly icon in the SQL view, you can formulate a query that is not processed by LibreOfficeDev and sent directly to the database engine.