Diseñar una consulta

La vista Diseñu de consulta dexa la creación y edición de consultes de bases de datos.

P'aportar a esti comandu...

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


Iconu de nota

La mayoría de les bases de datos utilicen consultes pa peñerar o ordenar les tables de bases de datos por qu'amuesen los rexistros nel equipu. Les vistes apurren les mesmes funciones que les consultes, pero nel sirvidor. Si la base de datos atopar nun sirvidor qu'almite vistes, pue utilizar felicidaes vistes pa peñerar los rexistros del sirvidor con cuenta d'acelerar el tiempu de visualización.


Iconu de nota

Al escoyer el comandu Crear vista de la ficha Tables d'un documentu de base de datos, va ver la ventana Diseñu de vista que ye similar a la ventana Diseñu de consulta que se describe equí.


Cuando se crea una consulta caltién la estructura de la ventana de Diseñu de consultes, lo cual nun asocede cuando se crea una vista.

La vista Diseñu

Pa crear una consulta, faiga clic nel iconu Consultes d'un documentu de base de datos y, de siguío, faiga clic en Crear consulta en vista Diseñu.

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.

Na parte cimera de la ventana de la vista Diseñu de consulta, amuésense los iconos de les barres Diseñu de consulta y Diseñu.

Si deseya probar una consulta, faiga doble clic nel nome de la consulta nel documentu de base de datos. La resultancia de la consulta amosar nuna tabla similar a la vista d'orixe de datos. Nota: la tabla que s'amuesa ye temporal.

Tecles de la vista Diseñu de consulta

Tecla

Función

F4

Vista previa

F5

Executar consulta

F7

Amestar tabla o consulta


Esaminar

When you open the query design for the first time, you see a dialog in which you must first select the table or query that will be the basis for your new query.

Faiga doble clic nos campos p'amestalos a la consulta. Arrastre y coloque pa definir relaciones.

Iconu de nota

Mientres el diseñu d'una consulta nun ye posible modificar les tables escoyíes.


Desaniciar tables

Pa desaniciar una tabla de la vista de diseñu, calque nel marxe cimeru de la ventana de la tabla y active el menú contestual. Cola orde Desaniciar va desaniciar la tabla de la vista de diseñu. Otra opción ye calcar la tecla (Supr).

Mover tables y modificar el so tamañu

Les tables y el so tamañu puen definise a voluntá. Pa mover una tabla calcar col mur'l marxe cimeru y llévase a la posición deseyada. P'aumentar o menguar el tamañu de presentación, arrastre'l borde escontra una de les esquines.

Relaciones ente tables

Les relaciones de datos que puen haber ente un nome de campu d'una tabla y unu d'otra tabla puen utilizase pa les consultes.

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.

Namái pue crease una consulta basada en delles fueyes rellacionaes si utilízase LibreOffice como interfaz pa una base de datos relacional.

Iconu de nota

Nuna consulta nun ye posible aportar a tables de bases de datos distintes. Les consultes de delles tables namái puen crease dientro d'una mesma 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.

Como alternativa, prima Tabulador hasta que la llinia escuéyase, depués prima MAYUSCULA+F10 p'amosar el menú contestual onde tien d'escoyerEditar. Delles bases de datos solo soporten un subconxuntu de posibles tipos de conexón.

Desaniciar relaciones

Pa desaniciar los enllaces ente dos tables, escueya col mur la llinia de enllaz y calque la tecla (Supr).

Tamién pue desaniciar les respectives entraes en Campos usaos nel diálogu Relaciones. O pue calcar el tabulador hasta que'l vector de conexón quede destacáu y depués calcar Mayús+F10 p'abrir el menú contestual y escoyer la orde Desaniciar.

Defining the query

Escueya condiciones pa definir la consulta. Cada columna de la tabla de diseñu aceuta un campu de datos pa la consulta. Les condiciones d'una filera enllazar con una espresión lóxica Y.

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.

Desaniciar nomes de campos

Pa desaniciar un campu de datos de la consulta, calque col mur na testera de la columna del campu y active el comandu Desaniciar del menú contestual de la 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

Escriba'l nome del esquema que s'asignó a la consulta o vista de tabla.

Nome de la consulta vista de tabla

Escriba'l nome de la vista de tabla o consulta.

Peneráu 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:

Campu

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.

Alies

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 column AS alíes FROM table.

Por exemplu:

SELECT "Ref." AS Referencia FROM "Artículos"

Tabla

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.

Visible

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.

o

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:

Funciones

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

Efeutu

Ensin función

Nun s'executa nenguna función

Promediu

AVG

Calcula la media aritmética d'un campu.

Count

COUNT

Determines the number of records in the table. Empty fields can either be counted (a) or excluded (b).

a) COUNT(*): Si introduz un asteriscu como argumentu calculen tolos rexistros de datos de la tabla.

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.

Maximum

MAX

Determines the highest value of a record for that field.

Mínimu

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.

Arrexuntar

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.


Tamién puen introducise llamaes a funciones directamente nuna espresión SQL. La sintaxis ye:

SELECT FUNCTION(column) FROM table.

En SQL la función pa sumar, por exemplu, presentar del mou siguiente:

SELECT SUM("Precios") FROM "Artículos".

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 instrucción SQL l'activación de la función presentar cola forma siguiente:

SELECT FUNCTION() AS alíes FROM table

Exemplu:

SELECT COUNT(*) AS cantidad FROM "Artículos"

Iconu de nota

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

Nel siguiente exemplu realízase una consulta en dos tables: una tabla "Artículos" col campu "Referencia" y otra tabla, "Provisores", col campu "nome_provisor". Amás, dambes tables disponen d'un campu de datos común llamáu "num_provisor".

Pa crear una consulta que contenga tolos provisores que suministren más de tres artículo, ye necesariu siguir los pasos siguientes:

  1. Introducir les tables "Artículos" y "Provisores" nel diseñu de la consulta.

  2. Rellacionar los campos "num_provisor" de dambes tables, sacante si yá s'estableció una rellación ente elles.

  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. Introducir >3 como criteriu y anubrir el campu visible.

  5. Faiga clic dos vegaes nel campu "nome_provisor" de la tabla "Provisores" y escoyer la función Arrexuntar.

  6. Execute la consulta.

Si na tabla "Artículu" esiste'l campu "Preciu" (preciu unitariu d'un artículu) y "Num_provisor" (provisor del artículu), el preciu mediu qu'aplica un provisor calcular cola siguiente consulta:

  1. Inxertar la tabla "Artículos" en Diseñar consulta.

  2. Calcar dos vegaes nel campu "Preciu" y nel campu "Num_provisor".

  3. Activar la filera Función y escoyer la función Promediu nel campu "Preciu".

  4. Opcionalmente pue introducise l'alies "Promediu" na filera (ensin comines).

  5. Escoyer Arrexuntar nel campu "Num_provisor".

  6. Execute la consulta.

Esisten los comandos de menú y símbolos siguientes:

Funciones

Shows or hides a row for the selection of functions.

Nome de tabla

Amuesa o anubre la filera del nome de la tabla.

Nome del Alies

Amuesa o anubre la filera del alies.

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 exemplu, si'l nome "Pérez" apaez delles vegaes na base de datos de direiciones, escueya la opción Valores inequívocos pa especificar na consulta que'l nome "Pérez" apaeza una sola vegada.

Nel casu d'una consulta qu'inclúi dellos campos, la combinación de valores de tolos campos tien de ser inequívoca, de cuenta que la resultancia pueda llograse a partir d'un rexistru específicu. Por exemplu, supongamos que la so axenda contién "Pérez de Madrid" una vegada y "Pérez de Barcelona" dos vegaes. La orde Valores inequívocos fai que la consulta utilice los campos "apellíu" y "ciudá" y devuelva como resultáu "Pérez de Madrid" una vegada y "Pérez de Barcelona" una vegada.

En SQL, esta orde correspuende al predicáu DISTINCT.

Llendes

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.

Formular condiciones de filtru

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

Significáu

La condición cumple si...

=

equal to

... el conteníu del campu ye idénticu a la espresión introducida.

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

... el conteníu del campu nun se correspuende cola espresión introducida.

>

greater than

... el conteníu del campu ye mayor que la espresión introducida.

<

less than

... el conteníu del campu ye menor que la espresión introducida.

>=

greater than or equal to

... el conteníu del campu ye idénticu o mayor que la espresión introducida.

<=

less than or equal to

... el conteníu del campu ye menor o igual que la espresión introducida.


Comandu de LibreOffice

Comandu SQL

Significáu

La condición cumple si...

IS EMPTY

IS NULL

ye nulu

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

is not empty

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

is an element of

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

Is not an element of

... the field does not contain data having the specified expression.

BETWEEN x AND y

BETWEEN x AND y

entendíu nel intervalu [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 entendíu nel intervalu [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...)

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

does not contain a, b, c...

... the field does not contain one of the specified expressions a, b, c,...

= TRUE

= TRUE

tien el valor True

... el campu de datos tien el valor Verdaderu.

= FALSE

= FALSE

tien el valor False

... the field data value is set to false.


Exemplos

='Ms.'

amuesa los campos de datos col conteníu "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".


LikeSecuencia d'escape: {escape 'escape-character'}

Por exemplu: select * from Articulo where Nom_articulo like 'The *%' {escape '*'}

Esti exemplu apurre toles entraes nes que'l nome del artículu empieza con 'The *'. Tamién ye posible guetar caráuteres, que de lo contrario s'interpreten como comodinos, por exemplu *, ?, _, % o'l puntu.

Outer Join Secuencia d'escape: {oj outer-join}

Por exemplu: select articulo.* from {oj articulo LEFT OUTER JOIN pidíos ON referencia=pidíos.ANR}

Consultes en campos de testu

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

Consultes en campos de feches

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]'


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

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

Consulta de campos Sí/Non

Pa peñerar los campos Si/Non de tables dBase, use la siguiente sintaxis:

Condición

Criteriu de consulta

Exemplu

Yes

en tables dBASE: nun ye igual a cualquier valor dáu

=1 apurre tolos rexistros de datos nos que'l campu Sí/Nun contién el criteriu "Sí" o "activáu" (caxellu señaláu).

Non

.

=0 apurre tolos rexistros de datos nos que'l campu Sí/Nun contién el criteriu "Non" o "desactiváu" (caxellu non señaláu).

Null

IS NULL

IS NULL amuesa tolos rexistros de datos nos que'l campu Sí/Non nun contién nin el criteriu Sí nin el criteriu Non (caxellu en gris).


Iconu de nota

La sintaxis depende del sistema de base de datos utilizáu. Tien De tener en cuenta que los campos Sí/non puen definise de forma distinta (namái 2 estaos en llugar de 3).


Consultes 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

Iconu d'alvertencia

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.


Iconu de conseyu

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.

Iconu de conseyu

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.


Mou SQL

SQL son les sigles de "Structured Query Language" y ye un llinguaxe que define les instrucciones pa consultar, anovar y alministrar bases de datos relacionales.

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.