Query Design

A vista Design de consulta permite-lhe criar e editar uma consulta de uma base de dados.

Para aceder a este comando...

Numa janela de ficheiros de base de dados, clique no ícone Consultas e escolha Editar - Editar.


note

A maioria das bases de dados utiliza consultas para filtrar ou ordenar as tabelas da base de dados e mostrar os registos no computador. As vistas oferecem a mesma funcionalidade que as consultas, mas ao nível do servidor. Se a base de dados estiver num servidor que suporte vistas, pode utilizar as vistas para filtrar os registos no servidor de modo a acelerar o tempo de exibição.


note

Ao selecionar o comando Criar vista no separador Tabelas em documento de uma base de dados, irá visualizar a janela Design de vista que é semelhante à janela Design de consulta aqui descrita.


O esquema da janela Design de consulta é armazenado com uma consulta criada, não sendo possível armazenar com uma vista criada.

Vista de design

Para criar uma consulta, clique no ícone Consultas no documento e, em seguida, clique em Criar consulta no modo de design.

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 superior da janela da vista de design, são mostrados os ícones da barra Design de consulta e da barra Design.

Se quiser testar uma consulta. clique duas vezes no nome da consulta. O resultado é mostrado em formato de tabela semelhante à Vista de origem de dados. Nota: a tabela apenas é mostrada temporariamente.

Chaves na vista de design de uma consulta

Chave

Função

F4

Pré-visualizar

F5

Executar consulta

F7

Adicionar tabela ou consulta


Explorar

Ao abrir o design de consulta pela primeira vez, surgirá uma caixa de diálogo na qual deverá escolher a tabela ou consulta que servirá de base à sua consulta.

Clique duas vezes nos campos para os adicionr à consulta. Arraste e solte para definir as relações.

note

Ao desenhar uma consulta, não pode modificar as tabelas selecionadas.


Remover tabelas

Para remover uma tabela da vista de design, clique na margem superior da janela da tabela para mostrar o menu de contexto. Pode utilizar o comando Eliminar para remover a tabela da vista. Outra possibilidade é premir a tecla Delete.

Mover tabelas e alterar o tamanho de tabelas

Pode redimensionar e dispor as tabelas da forma que pretender. Para mover tabelas, arraste a margem superior para a posição pretendida. Aumente ou reduza a dimensão na qual a tabela é apresentada posicionando o cursor do rato numa margem ou canto e arrastando a tabela até que esta tenha a dimensão pretendida.

Relações de tabela

Se as relações de dados entre um nome de campo de uma tabela e um nome de campo de outra tabela, pode utilizar as relações na sua consulta.

Se, por exemplo, tiver uma folha de cálculo para artigos identificados por um número de artigo e uma folha de cálculo para clientes, na qual regista de todos os artigos encomendados por um cliente utilizando os números de artigo correspondentes, existe uma relação entre os dois campos de dados "número de artigo". Se pretender agora criar uma consulta que tenha como resultado todos os artigos que um cliente tenha encomendado, deverá obter os dados a partir de duas folhas de cálculo. Para tal, deverá comunicar ao LibreOffice qual a relação existente entre os dados nas duas folhas de cálculo.

Para executar este procedimento, clique num nome de campo numa tabela (por exemplo, o nome do campo "Artigo-Número" da tabela Cliente), continue a premir o botão do rato e, em seguida, arraste o nome de campo para o nome de campo da outra tabela ("Artigo-Número" da tabela Artigo). Assim que soltar o botão do rato, surge uma linha que estabelece uma ligação entre os dois campos nas duas janelas. A condição correspondente de que o conteúdo dos dois nomes dos campos sejam idênticos é introduzida na consulta SQL resultante.

A criação de uma consulta baseada em várias folhas só é possível se utilizar o LibreOffice como interface para uma base de dados relacional.

note

Não é possível aceder a tabelas de diferentes bases de dados numa consulta. As consultas que envolvam várias tabelas só podem ser criadas dentro de uma única base de dados.


Especificar o tipo de relação

Se clicar duas vezes na linha que liga dois campos vinculado,s ou chamar o comando de menu Inserir - Nova relação, poderá especificar o tipo de relação na caixa de diálogo Relações.

Em alternativa, prima a tecla Tab até que o vetor de união esteja selecionado e prima as teclas Shift+F10 para abrir o menu de contexto onde poderá escolher o comando Editar. Algumas bases de dados apenas permitem um subconjunto dos tipos de união possíveis.

Eliminar relações

Para eliminar uma relação entre duas tabelas, clique na linha de ligação e prima a tecla Delete.

Em alternativa, elimine as entradas correspondentes nos Campos utilizados na caixa de diálogo Relações. Ou prima a tecla Tab até que o vetor de ligação seja destacado, prima as teclas Shift+F10 para abrir o menu de contexto e selecione o comando Eliminar.

Definir uma consulta

Selecione as condições para definir a consulta. Cada coluna da tabela de design aceita um campo de dados para a consulta. As condições de uma linha são associadas por um E booleano.

Especificar nome de campos

Em primeiro lugar, selecione todos os nomes de campos das tabelas que pretender adicionar à consulta. Pode fazê-lo pelo processo arrastar e largar, ou clicando duas vezes num nome de um campo na janela da tabela. Com o método arrastar e largar, utilize o rato para arrastar um nome de um campo a partir da janela da tabela até à área inferior do design de consulta. Enquanto faz isto, pode decidir a qual coluna pretende adicionar o campo. Selecione um nome de um campo clicando duas vezes sobre o mesmo. Este será adicionado à próxima coluna que esteja livre.

Eliminar nomes dos campos

Para remover um nome de um campo da consulta, clique no cabeçalho de coluna do campo e escolha o comando Eliminar no menu de contexto.

Guardar uma consulta

Utilize o ícone Guardar na barra Padrão para guardar a consulta. Verá uma caixa de diálogo a solicitar a introdução de um nome para a consulta. Se a base de dados suportar esquemas, também é possível introduzir um nome de esquema.

Esquema

Introduza o nome do esquema que foi atribuído à vista de consulta ou de tabela.

Nome da consulta ou da vista de tabela

Introduza o nome da consulta ou da vista de tabela.

Filtrar dados

Para filtrar dados para a consulta, defina as preferências na área inferior da janela do design de consulta. Estão disponíveis as seguintes opções:

Campo

Introduza o nome do campo de dados ao qual se refere na Consulta. Todas as definições estabelecidas nas linhas inferiores referem-se a este campo. Se ativar uma célula através de um clique do rato, irá visualizar um botão de seta que permite selecionar um campo. A opção "Table name.*" seleciona todos os campos de dados e os critérios são válidos para todos os campos das tabelas.

Nome alternativo

Especifica um nome alternativo. Este nome alternativo será listado numa consulta em vez do nome do campo. Este procedimento faz com que seja possível utilizar etiquetas de coluna definidas pelo utilizador. Por exemplo, se o campo de dados tiver o nome PtNo e, em vez desse nome, preferir que apareça PartNum na consulta, introduza PartNum como nome alternativo.

Numa instrução SQL, os nomes alternativos são definidos da seguinte forma:

SELECT coluna AS alias FROM tabela.

Por exemplo:


SELECT "PtNo" AS "PartNum" FROM "Parts"

Tabela

A tabela da base de dados correspondente do campo de dados selecionado é aqui listada. Se ativar a célula com um clique do rato, irá surgir uma seta que lhe permite selecionar outra tabela da consulta atual.

Ordenação

Ao clicar nesta célula, pode selecionar as opções de ordenação: ascendente, descendente e sem ordenação. Os campos de textos serão ordenados alfabeticamente, e os campos numéricos serão ordenados numericamente. Na maior parte das bases de dados, os administradores podem definir as opções de ordenação.

Visível

Se assinalar a propriedade Visível para um campo de dados, esse campo estará visível na consulta. Se utilizar apenas um campo de dados para formular uma condição, não é obrigatório que este seja visualizado.

Critérios

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

ou

Pode inserir aqui um critério adicional para filtragem em cada linha. Critérios múltiplos numa única coluna serão interpretados como um OU booleano.

Também pode utilizar o menu de contexto dos cabeçalhos de linha na área inferior do design de consulta para inserir um filtro para as funções:

Funções

As funções disponíveis aqui dependem daquelas fornecidas pelo motor do banco de dados.

Se estiver a trabalhar com a base de dados HSQL incorporada, a caixa de lista na linha Funções disponibiliza-lhe as seguintes opções:

Opção

SQL

Efeito

Sem função

Não será executada qualquer função.

Média

AVG

Calcula a média aritmética de um campo.

Contagem

COUNT

Determina o número de registos da tabela. Os campos vazios tanto podem ser contados (a), como excluídos (b).

a) COUNT(*): Para contar todos os registos da tabela, passe um asterisco como argumento.

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

Agrupa os dados da consulta de acordo com o nome do campo. As funções são executadas de acordo com os grupos especificados. Em SQL, esta opção corresponde à expressão GROUP BY. Se for adicionado um critério, esta entrada surge na sub-cláusula SQL HAVING.


Também é possível invocar uma função diretamente na instrução SQL. A sintaxe é:

SELECT FUNCTION(coluna) FROM tabela.

Por exemplo, a chamada de função em SQL para calcular uma soma é:


SELECT SUM("Price") FROM "Article".

Com exceção da função Agrupar, as funções acima são denominadas Funções agregadas. Estas funções calculam dados para criar resumos a partir dos resultados. Também podem estar disponíveis funções adicionais que não são apresentadas na caixa de lista. Estas dependem do sistema de base de dados específico em utilização e do estado atual do controlador do Base.

Para utilizar uma função que não esteja listada, tem de as introduzir manualmente em Campo.

Também é possível atribuir nomes alternativos a chamadas de função. Se não pretender que a consulta seja visualizada no cabeçalho da coluna, introduza o nome pretendido em Nome alternativo.

A função correspondente numa instrução SQL é:

SELECT FUNCTION() AS alias FROM tabela

Example:


SELECT COUNT(*) AS count FROM "Item"
note

Se executar esta função, não poderá inserir colunas adicionais para a consulta, mas apenas recebê-las como uma função de "Agrupar".


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.

  1. Insert the "Item" and "Suppliers" tables into the query design.

  2. Link the "Supplier_No" fields of the two tables if there is not already a relation of this type.

  3. Clicar duas vezes no campo "Item_No" da tabela "Item". Para mostrar a linha Função, utilize o menu de contexto e selecione a função Contar.

  4. Enter >3 as a criterion and disable the Visible field.

  5. Clique duas vezes no campo "Supplier_Name" da tabela "Suppliers" e escolha a função Agrupar.

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

  1. Insert the "Item" table into the query design.

  2. Double-click the "Price" and "Supplier_No" fields.

  3. Ative a linha Função e selecione a função Média do campo "Preço".

  4. You can also enter "Average" in the line for the alias name (without quotation marks).

  5. Choose Group for the "Supplier_No" field.

  6. Run the query.

The following context menu commands and symbols are available:

Funções

Mostra ou oculta uma linha para a seleção de funções.

Table Name

Mostra ou oculta a linha para o nome da tabela.

Alias Name

Mostra ou oculta a linha para o nome alternativo.

Distinct Values

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.

Limit

Permite-lhe limitar o número máximo de registos devolvido por uma consulta.

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.

Formulating filter conditions

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:

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.


LibreOffice command

SQL command

Meaning

Condition is satisfied if...

IS EMPTY

IS NULL

is null

... 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 contains the indicated expression. The (*) placeholder indicates whether the expression x occurs at the beginning of (x*), at the end of (*x) or inside the field content (*x*). You can enter as a placeholder in SQL queries either the SQL % character or the familiar (*) file system placeholder 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

falls within the interval [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

Does not fall within the interval [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

has the value True

... the field name has the value True.

= FALSE

= FALSE

has the value false

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


Examples

='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'}

Example:


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}

Example:


SELECT Article.* FROM {oj item LEFT OUTER JOIN orders ON item.no=orders.ANR}

Querying text fields

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

Querying date fields

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


Example:


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

Querying Yes/No fields

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


note

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

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

warning

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.


tip

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.

Parameter Input

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.

tip

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 Mode

SQL stands for "Structured Query Language" and describes instructions for updating and administering relational databases.

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.

Necessitamos da sua ajuda!