Módulo
Contido
Índice 🔎︎

# Deseño de consulta

A opción Visualización de deseño de consulta permite crear e editar consultas de bases de datos.

Para acceder a esta orde...

In a database file window, click the Queries icon, then choose Edit - Edit.

A maioría das bases de datos utilizan consultas para filtrar ou ordenar táboas de bases de datos e mostrar rexistros no seu computador. As visualizacións ofrecen a mesma funcionalidade que as consultas, mais do lado do servidor. Se a súa base de datos está nun servidor que soporta visualizacións, pode utilizalas para filtrar os rexistros no servidor e, así, acelerar o tempo de visualización.

Selecting the Create View command from the Tables tab page of a database document, you see the View Design window that resembles the Query Design window described here.

The Query Design window layout is stored with a created query, but cannot be stored with a created view.

## A visualización de deseño

Para crear unha consulta, prema na icona Consultas dun documento de base de datos e, a seguir, prema en Crear consulta na visualización de deseño.

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 Command Ctrl+arrow key.

Na parte superior da xanela Visualización de deseño de consulta móstranse as iconas das barras Deseño de consulta e Deseño.

Se desexa probar unha consulta, prema dúas veces no seu nome no documento. O resultado móstrase nunha táboa semellante á Visualización de fonte de datos. Nota: A táboa que se mostra é temporal.

### Teclas na Visualización de deseño de consulta

Chave | Función
F4 | Previsualización
F5 | Executar consulta
F7 | Engadir táboa ou consulta

## Explorar

A primeira vez que se abre o deseño de consultas vese unha caixa de diálogo na que primeiro hai que seleccionar a táboa ou consulta que será a base para a nova consulta.

Prema dúas veces nos campos para engadilos á consulta. Arrastre e solte para definir as relacións.

Mentres deseña unha consulta non pode modificar as táboas seleccionadas.

### Eliminar táboas

Para eliminar a táboa da Visualización de deseño, prema no bordo superior da xanela da táboa e, no menú de contexto, use a orde Eliminar. Outra opción é premer na tecla Suprimir.

### Mover táboas e modificar o seu tamaño

Pode redimensionar e dispor as táboas como prefira. Para movelas, arrastre o seu bordo superior ata a posición que desexe. Para ampliar ou reducir o seu tamaño, posicione o cursor do rato sobre un bordo ou canto e arrastre.

## Relacións entre táboas

Se hai relación entre os datos de dous nomes de campo pertencentes a dúas táboas diferentes, pode usar esas relacións para a súa consulta.

If, for example, you have a spreadsheet for articles identified by an article number, and a spreadsheet for customers in which you record all articles that a customer orders using the corresponding article numbers, then there is a relationship between the two "article number" data fields. If you now want to create a query that returns all articles that a customer has ordered, you must retrieve data from two spreadsheets. To do this, you must inform LibreOffice about the relationship which exists between the data in the two spreadsheets.

To do this, click a field name in a table (for example, the field name "Item-Number" from the Customer table), hold down the mouse button and then drag the field name to the field name of the other table ("Item-Number" from the Item table). When you release the mouse button, a line connecting the two fields between the two table windows appears. The corresponding condition that the content of the two field names must be identical is entered in the resulting SQL query.

A creación dunha consulta baseada en varias follas de cálculo relacionadas só é posíbel cando se usa LibreOffice como interface dunha base de datos relacional.

Nas consultas non é posíbel acceder a táboas de diferentes bases de datos. As consultas relacionadas con varias táboas só poden crearse dentro dunha única base de datos.

### Specifying the relation type

If you double-click on the line connecting two linked fields or call the menu command Insert - New Relation, you can specify the type of relation in the Relations dialog.

Alternatively, press Tab until the line is selected, then press Shift+F10 to display the context menu and there choose the command Edit. Some databases support only a subset of the possible join types.

### Eliminar relacións

Para eliminar unha relación entre dúas táboas, prema na liña de conexión e, a seguir, na tecla Suprimir.

Outra posibilidade é eliminar as entradas correspondentes en Campos implicados, na caixa de diálogo Relacións. Tamén pode premer na tecla Tab ata seleccionar o vector de conexión, despois premer en Maiús+F10 para abrir o menú de contexto e finalmente seleccionar a orde Eliminar.

## Defining the query

Seleccione as condicións para definir a consulta. Cada columna da táboa de deseño acepta un campo de datos. As condicións das filas líganse mediante o E booleano.

### Specifying field names

First, select all field names from the tables that you want to add to the query. You can do this either by drag-and-drop or by double-clicking a field name in the table window. With the drag-and-drop method, use the mouse to drag a field name from the table window into the lower area of the query design window. As you do this, you can decide which column in the query design window will receive the selected field. A field name can also be selected by double-clicking. It will then be added to the next free column in the query design window.

### Eliminar nomes de campos

Para eliminar un nome de campo da consulta, prema na cabeceira da columna do campo e escolla a orde Eliminar no menú de contexto da columna.

### Saving the query

Use the Save icon on the Standard toolbar to save the query. You will see a dialog that asks you to enter a name for the query. If the database supports schemas, you can also enter a schema name.

#### Esquema

Introduza o nome do esquema atribuído á consulta ou á visualización de táboas.

#### Nome de consulta ou nome de visualización de táboa

Introduza o nome de consulta ou de visualización de táboa.

### Filtraxe de datos

To filter data for the query, set the desired criteria in the lower area of the query design window. The following options are available:

#### Campo

Enter the name of the data field that is referred to in the Query. All settings made in the filter option rows refer to this field. If you activate a cell here with a mouse click you'll see an arrow button, which enables you to select a field. The "Table name.*" option selects all data fields with the effect that the specified criteria will be applied to all table fields.

#### Alcume

Specifies an alias. This alias will be listed in the query instead of the field name. This makes it possible to use user-defined column labels. For example, if the data field is named PtNo and, instead of that name, you would like to have PartNum appear in the query, enter PartNum as the alias.

In a SQL statement, aliases are defined as follows:

SELECT columna AS alcume FROM táboa.

Por exemplo:

SELECT "Compostela" AS "Santiago" FROM "Historia"

#### Táboa

The corresponding database table of the selected data field is listed here. If you activate this cell with a mouse click, an arrow will appear which enables you to select a different table for the current query.

#### Ordenar

If you click on this cell, you can choose a sort option: ascending, descending and unsorted. Text fields will be sorted alphabetically and numerical fields numerically. For most databases, administrators can set the sorting options at the database level.

#### Visíbel

If you mark the Visible property for a data field, that field will be visibly displayed in the resulting query. If you are only using a data field to formulate a condition or make a calculation, you do not necessarily need to display it.

#### Criterios

Specifies a first criteria by which the content of the data field is to be filtered.

#### ou

Here you can enter one additional filter criterion for each line. Multiple criteria in a single column will be interpreted as boolean OR.

You can also use the context menu of the line headers in the lower area of the query design window to insert a filter based on a function:

### Funcións

The functions which are available here depend on those provided by the database engine.

If you are working with the embedded HSQL database, the list box in the Function row offers you the following options:

Opción | SQL | Efecto
Sen función |  | Non se executa ningunha opción.
Media | AVG | Calcula a media aritmética dun campo.
Conta | COUNT | Determines the number of records in the table. Empty fields can either be counted (a) or excluded (b). a) COUNT(*): Introducindo un asterisco como argumento, cóntanse todos os rexistros da táboa. b) COUNT(column): Passing a field name as an argument counts only those records for fields in which the field name in question contains a value. Records with fields having Null values (i.e. fields containing no characters) will not be counted.
Máximo | MAX | Determines the highest value of a record for that field.
Mínimo | MIN | Determines the lowest value of a record for that field.
Suma | SUM | Calculates the sum of the values of records for the associated fields.
Agrupar | 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.

Tamén pode introducir chamadas de función directamente na instrución SQL. A sintaxe é:

SELECT FUNCTION(columna) FROM táboa.

Por exemplo, a chamada de función en SQL para calcular unha suma é:

SELECT SUM("Prezo") FROM "Artigo".

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.

Na linguaxe SQL a función correspondente é a seguinte:

SELECT FUNCTION() AS alcume FROM táboa

Exemplo:

SELECT COUNT(*) AS conta FROM "Artigo"

If you run such a function, you cannot insert any additional columns for the query other than as an argument in a "Group" function.

Exemplos

No seguinte exemplo, execútase unha consulta entre dúas táboas: unha chámase "Artigo", co campo "Número de artigo", e a outra "Fornecedores", co campo "Nome de fornecedor". Alén diso, ambas as táboas posúen un nome de campo común: "Número de fornecedor."

Para crear consultas que conteñan os fornecedores que entregan máis de tres artigos, é preciso seguir estes pasos:

1. Introduza as táboas "Artigo" e "Fornecedores" no deseño de consulta.

2. Ligue os campos "Número de fornecedor" das dúas táboas, se non existe xa relación entre elas.

3. Double-click on the "Item_No" field from the "Item" table. Display the Function line using the context menu and select the Count function.

4. Introduza >3 como criterio e desactive o campo Visíbel.

5. Prema dúas veces no campo "Nome de fornecedor" da táboa "Fornecedores" e escolla a función Agrupar.

6. Executar a consulta.

Se existen os campos "Prezo" (para o prezo de cada artigo) e "Número de fornecedor" (para o fornecedor do artigo) na táboa "Artigo", pode obter o prezo medio do artigo provisto polo fornecedor por medio da seguinte consulta:

1. Insira a táboa "Artigo" no deseño de consulta.

2. Prema dúas veces nos campos "Prezo" e "Número de fornecedor".

3. Active a liña Función e seleccione a función Media no campo "Prezo".

4. Tamén pode introducir "Media" na liña do alcume (sen comiñas).

5. Para o campo "Número de fornecedor", escolla Agrupar.

6. Executar a consulta.

Están dispoñíbeis os seguintes símbolos e ordes de menú de contexto:

### Funcións

Shows or hides a row for the selection of functions.

### Nome da táboa

Mostra ou oculta a fila do nome de táboa.

### Alcume

Mostra ou oculta a fila do alcume.

### Valores unívocos

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).

Por exemplo, se o nome "Castro Leiro" se repite na súa base de datos de enderezos, pode escoller a orde Valores unívocos para especificar na consulta que o nome "Castro Leiro" apareza só unha vez.

Se unha consulta abarca varios campos, a combinación de valores dos campos debe ser exclusiva, de modo que o resultado se poida formar desde un rexistro específico. Por exemplo, se "Castro Leiro na Guarda" aparece na axenda de enderezos unha vez e "Castro Leiro en Guimarães" dúas, coa orde Valores unívocos a consulta usará os dous campos, "Apelidos" e "Cidade", devolvendo unha vez o resultado "Castro Leiro na Guarda" e outra "Castro Leiro en Guimarães".

En SQL, esta orde corresponde ao predicado DISTINCT.

### Límite

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.

### Formulación de condicións de filtraxe

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 LibreOffice syntax, LibreOffice 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:

Operador | Significado | Cúmprese a condición se...
= | igual a | ... o contido do campo é identico á expresión indicada. The operator = will not be displayed in the query fields. If you enter a value without any operator, the = operator is automatically assumed.
<> | diferente de | ... o contido do campo non se corresponde coa expresión especificada.
> | maior que | ... o contido do campo é maior que a expresión especificada.
< | menor que | ... o contido do campo é menor que a expresión especificada.
>= | maior que ou igual a | ... o contido do campo é maior que ou igual á expresión especificada.
<= | menor que ou igual a | ... o contido do campo é menor que ou igual á expresión especificada.

Orde de LibreOffice | Orde SQL | Significado | Cúmprese a condición se...
IS EMPTY | IS NULL | é nulo | ... the field contains no data. For Yes/No fields with three possible states, this command automatically queries the undetermined state (neither Yes nor No).
IS NOT EMPTY | IS NOT NULL | non está baleiro | ... the field is not empty, i.e it contains data.
LIKE placeholder (*) for any number of characters placeholder (?) for exactly one character | LIKE placeholder (%) for any number of characters Placeholder (_) for exactly one character | é un elemento de | ... the data field must contain the indicated search string in the order given. The position of the (*) placeholder indicates whether the searched for string (x) occurs before the placeholder (x*), after the placeholder (*x) or between the placeholders (*x*). Instead of the familiar file system (*) placeholder, you can also use the SQL (%) character as a placeholder in SQL queries in the LibreOffice interface. The (*) or (%) placeholder stands for any number of characters. The question mark (?) in the LibreOffice interface or the underscore (_) in SQL queries is used to represent exactly one character.
NOT LIKE | NOT LIKE | non é un elemento de | ... the field does not contain data having the specified expression.
BETWEEN x AND y | BETWEEN x AND y | encóntrase no intervalo [x,y] | ... the field contains a data value that lies between the two values x and y.
NOT BETWEEN x AND y | NOT BETWEEN x AND y | Non se encontra no intervalo [x,y] | ... the field contains a data value that does not lie between the two values x and y.
IN (a; b; c...) Note that semicolons are used as separators in all value lists! | IN (a, b, c...) | contén a, b, c... | ... the field name contains one of the specified expressions a, b, c,... Any number of expressions can be specified, and the result of the query is determined by a boolean OR operator. The expressions a, b, c... can be either numbers or characters
NOT IN (a; b; c...) | NOT IN (a, b, c...) | non contén a, b, c... | ... the field does not contain one of the specified expressions a, b, c,...
= TRUE | = TRUE | ten o valor verdadeiro | ... o nome de campo ten o valor verdadeiro.
= FALSE | = FALSE | ten o valor falso | ... the field data value is set to false.

### Exemplos

='Ms.' | devolve os nomes de campo que conteñen "Sra."
<'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".

Secuencia de escape Like: {escape 'carácter de escape'}

Exemplo: select * from Elemento where Nomedeelemento like 'O *%' {escape '*'}

Así devolveránse todas as entradas en que o nome de elemento comece por 'O *', o que significa que tamén é posíbel procurar caracteres que doutra maneira se interpretarían como marcadores de posición, como *, ?, _, % ou o punto.

Secuencia de escape: Outer Join: {oj outer-join}

Exemplo: select Artigo.* from {oj elemento LEFT OUTER JOIN pedidos ON elemento.no=pedidos.ANR}

### Consulta de campos de texto

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).

### Consulta de campos de data

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 | Sintaxe de SQL2
Data | {D'YYYY-MM-DD'} | {d 'YYYY-MM-DD'} | 'YYYY-MM-DD'
Hora | {D'HH:MM:SS'} | {t 'HH:MI:SS[.SS]'} | 'HH:MI:SS[.SS]'
DataHora | {D'YYYY-MM-DD HH:MM:SS'} | {ts 'YYYY-MM-DD HH:MI:SS[.SS]'} | 'YYYY-MM-DD HH:MI:SS[.SS]'

Exemplo: select {d '1999-12-31'} from world.years

Exemplo: select * from amiñatáboa 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.)

### Consulta en campos Si/Non

To query Yes/No fields, use the following syntax for dBASE tables:

Estado | Criterio de consulta | Exemplo
Si | for dBASE tables: not equal to any given value | =1 devolve os rexistros en que o campo Si/Non ten o estado "Si" ou "Activado" (seleccionados en negro),
Non | . | =0 devolve os rexistros en que o campo Si/Non ten o estado "Non" ou "Desactivado" (sen selección).
Nulo | IS NULL | IS NULL devolve os rexistros en que o campo Si/Non nin ten o estado Si nin o estado Non (seleccionados en gris).

A sintaxe depende do sistema de base de datos usado. Teña en conta tamén que os campos Si/Non poden definirse de forma diferente (só dous estados, en vez de tres).

### Consultas de parámetros

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.

### Entrada de parámetros

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.

## Modo SQL

SQL son as siglas de "Structured Query Language", unha linguaxe que permite a utilización de instrucións para a actualización e administración de bases de datos relacionais.

In LibreOffice 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, LibreOffice 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 LibreOffice and sent directly to the database engine.