Kyselyn suunnittelu

Kyselyn suunnittelunäkymässä luodaan ja muokataan tietokantakyselyjä.

Toiminnon käyttäminen:

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


Huomautus-kuvake

Useimmat tietokannat käyttävät kyselyjä tietokantataulun tietokoneella esitettävien tietueiden suodattamiseen tai lajittelemiseen. Näkymissä on samat toiminnot kuin kyselyissä, mutta ne toimivat palvelimella. Jos tietokanta on näkymiä tukevalla palvelimella, näkymiä voidaan käyttää tietueiden suodattamiseen palvelimella, jolloin tietojen esittäminen nopeutuu.


Huomautus-kuvake

Valitsemalla Luo näkymä -komento tietokanta-asiakirjan Taulut-välilehdeltä saadaan esille Näkymän suunnittelu -ikkuna, joka muistuttaa Kyselyn suunnittelu -ikkunaa, jota tässä kuvataan.


Kyselyn suunnittelun ikkunan asettelu tallennetaan luotavan kyselyn kera, mutta asettelua ei voi tallentaa luotavaan näkymään.

Suunnittelu-näkymä

Kyselyn luominen aloitetaan napsauttamalla Kyselyt-kuvaketta tietokanta-asiakirjassa ja napsauttamalla sitten Luo kysely rakennenäkymässä -valintaa.

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.

Kyselyn suunnittelun ikkunan yläosassa on näkyvissä Kysely- ja Suunnittelu-palkin kuvakkeet.

Kun kyselyä halutaan testata, kaksoisnapsautetaan kyselyn nimeä tietokanta-asiakirjassa. Kyselyn tulokset esitetään tietolähdenäkymän tapaan. Esitetty taulu on vain tilapäinen.

Kyselyn suunnittelunäkymän näppäimet

Näppäin

Toiminto

F4

Esikatselu

F5

Kysely suoritus

F7

Taulun tai kyselyn lisäys


Selaa

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.

Kenttä lisätään kyselyyn kaksoisnapsauttamalla. Taulujen välinen suhde määritellään vetämällä ja pudottamalla.

Huomautus-kuvake

Kyselyä suunniteltaessa ei voi muuttaa valittuja tauluja.


Taulujen poisto

Taulu poistetaan suunnittelunäkymästä siten, että napsautetaan tauluikkunan yläreunaa ja sitten otetaan esille kohdevalikko (kakkospainikkeella). Poista-komennolla poistetaan taulu suunnittelunäkymästä. Toinen vaihtoehto on painaa Delete-näppäintä kohdistetussa tauluikkunassa.

Tauluikkunan siirto ja koon muuttaminen

Tauluikkunat ovat kooltaan muuteltavissa ja järjesteltävissä työtilaan tarpeen mukaan. Taulu siirretään uuteen paikkaan vetämällä hiirellä yläreunasta. Tauluikkunan kokoa muutetaan sijoittamalla hiiri ikkunan reunaan tai nurkkaan ja vetämällä se tarvittavaan kokoon.

Taulujen suhteet

Jos yhden taulun kenttänimen ja toisen taulun kenttänimen välillä on suhde, näitä suhteita eli yhteyksiä voidaan käyttää kyselyssä.

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.

Useisiin taulukoihin perustuvan kyselyn luominen on mahdollista vain, jos LibreOfficea käytetään relaatiotietokannan käyttöliittymänä.

Huomautus-kuvake

Kyselyllä ei pääse käsiksi eri tietokantojen tauluihin. Useita tauluja käsittelevät kyselyt voidaan luoda vain yhdelle tietokannalle.


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.

Vaihtoehtoisesti painellaan Sarkainta kunnes viiva tulee valituksi ja sitten painetaan Vaihto+F10 kohdevalikon esille saamiseksi. Siitä valitaan Muokkaa. Joissakin tietokannoissa tuetaan vain mahdollisten liitostyyppien osajoukkoa.

Suhteiden poisto

Kahden taulun välisen suhde poistetaan napsauttamalla liitosviivaa ja painamalla sitten Delete-näppäintä.

Vaihtoehtoisesti poistetaan vastaavat merkinnät Sisällytettävät kentät -alueelta Liitoksen ominaisuudet-valintaikkunassa. Tai painellaan Sarkainta kunnes yhdistysviiva tulee korostetuksi ja painetaan sitten Vaihto+F10 kohdevalikon avaamiseksi. Lopuksi valitaan Poista-komento.

Defining the query

Valitaan kyselyn määrittelyn ehdot. Jokainen suunnittelutaulukon sarake lisää yhden tietokentän kyselyyn. Yhden rivin ehdot yhdistetään Boolen AND-operaattorilla (JA).

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.

Kenttänimien poistaminen

Kenttänimen poistamiseksi kyselystä napsautetaan kakkospainikkeella kentän sarakeotsikkoa ja valitaan Poista-komento sarakkeen kohdevalikosta.

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.

Kaavio

Nimetään kyselylle tai taulun näkymälle määrätty kaavio.

Kyselyn nimi tai näkymän nimi

Nimetään kysely tai taulun näkymä.

Tietojen suodatus

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

Kenttä

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.

Tunnus

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 sarake AS tunnus FROM taulu.

Esimerkiksi:

SELECT "PtNo" AS "Osanumero" FROM "Parts"

Taulu

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.

Lajittele

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.

Näkyvissä

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.

Ehto

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

tai

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:

Toiminnot

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:

Asetus

SQL

Tulos

Ei funktiota

Mitään toimintoa ei suoriteta.

Keskiarvo

AVG

Lasketaan kentän aritmeettinen keskiarvo.

Lukumäärä

COUNT

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

a) COUNT(*): välitettäessä asteriski argumenttina taulun kaikki tietueet otetaan lukuun.

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.

Enintään

MAX

Determines the highest value of a record for that field.

Vähintään

MIN

Determines the lowest value of a record for that field.

Summa

SUM

Calculates the sum of the values of records for the associated fields.

Ryhmittele

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.


Funktiokutsu voidaan kirjoittaa myös suoraan SQL-lauseeseen. Syntaksi on:

SELECT FUNCTION(sarake) FROM taulu.

Esimerkiksi SQL:än summan laskemisen funktiokutsu on:

SELECT SUM("yksikkoHinta") FROM "Tuotteet".

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.

Vastaava funktio SQL-lauseessa on:

SELECT FUNCTION() AS tunnus FROM taulu

Esimerkki:

SELECT COUNT( * ) AS "Lukumäärä" FROM "Tuotteet"

Huomautus-kuvake

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


Esimerkkejä

Alla olevassa esimerkissä kysely suoritetaan kahdesta taulusta: "Tuotteet"-taulusta "tuoteTunnus"-kentän kera ja "Toimittajat"-taulusta "toimittajaNimi"-kentän kera. Lisäksi molemmissa tauluissa on yhteinen kenttä, nimeltään "toimittajaTunnus".

Seuraavat vaiheet on tarvitaan, että saadaan luotua kysely, jossa on kaikki ne toimittajat, jotka toimittavat useampaa kuin kolmea tuotetta.

  1. Lisää "Tuotteet"- ja "Toimittajat"-taulut kyselyn suunnitteluun.

  2. Liitä kummankin taulun "toimittajaTunnus" -kentät, jos niiden välillä ei vielä ole suhdetta.

  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. Syötä ehdoksi >3 ja tyhjennä Näkyvissä-ruutu.

  5. Kaksoisnapsauta "toimittajaNimi"-kenttää "Toimittajat"-taulussa ja valitse Ryhmä-funktio.

  6. Suorita kysely.

Jos "Tuotteet"-taulussa on kentät "yksikkoHinta" (yhden artikkelin hinnalle) ja "toimittajaTunnus" (artikkelin toimittajalle), toimittajalta saatujen tuotteiden keskihinnan saa selville seuraavalla kyselyllä:

  1. Lisää "Tuotteet"-taulu kyselyn suunnitteluun.

  2. Kaksoisnapsauta "yksikkoHinta"- ja "toimittajaTunnus"-kenttiä.

  3. Ota käyttöön Funktio-rivi ja valitse Average-funktio "yksikkoHinta"-kentälle.

  4. "Average" voidaan syöttää myös tunnusriville (lainausmerkeittä).

  5. Valitse Ryhmä-funktio "toimittajaTunnus"-kentälle.

  6. Suorita kysely.

Seuraavat kohdevalikon komennot ja symbolit ovat saatavilla:

Toiminnot

Shows or hides a row for the selection of functions.

Taulun nimi

Esitetään tai piilotetaan taulun nimen rivi.

Alias-tunnus

Esitetään tai piilotetaan tunnusnimen rivi.

Erityisarvot

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

Esimerkiksi, jos nimi "Smith" esiintyy useita kertoja osoitetietokannassa, voidaan valita Erityisarvot-komento, joka määrittää kyselyn niin, että nimi "Smith" esiintyy vain kerran.

Useita kenttiä kattavissa kyselyissä kaikkien kenttien yhdistelmän tulee olla yksilöllinen, jotta kyseisen tietueen tulos esitetään. Esimerkiksi "Smith Chicagosta" esiintyy kerran osoitekirjassa ja "Smith Lontoosta" kahdesti. Kysely Erityisarvot-komennoin käyttää sekä "sukunimi"- että "kaupunki"-kenttää ja palauttaa kyselyn tuloksessa "Smithin Chicagosta" kerran ja "Smithin Lontoosta" kerran.

SQL:äsä tämä komento vastaa DISTINCT-predikaattia.

Raja-arvo

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.

Muodostetaan suodatusehdot

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:

Operaattori

Selite

Ehto täyttyy, jos ...

=

yhtä suuri kuin

... kentän sisältö vastaa täysin ilmoitettua lauseketta.

The operator = will not be displayed in the query fields. If you enter a value without any operator, the = operator is automatically assumed.

<>

eri suuri kuin

... kentän sisältö ei vastaa määritettyä lauseketta.

>

suurempi kuin

... kentän sisältö on suurempi kuin määritetty lauseke.

<

pienempi kuin

... kentän sisältö on pienempi kuin määritetty lauseke.

>=

suurempi tai yhtä suuri kuin

... kentän sisältö on suurempi tai yhtä suuri kuin määritetty lauseke.

<=

pienempi tai yhtä suuri kuin

... kentän sisältö on pienempi tai yhtä suuri kuin määritetty lauseke.


LibreOffice-komento

SQL-lause

Selite

Ehto täyttyy, jos ...

IS EMPTY

IS NULL

on tyhjä

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

ei ole tyhjä

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

on alkiona

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

ei ole alkiona

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

BETWEEN x AND y

BETWEEN x AND y

kuuluu suljettuun väliin [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

ei osu välille [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...)

sisältää 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...)

ei sisällä a, b, c...

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

= TRUE

= TRUE

arvona on TRUE

... kentän arvo on TRUE.

= FALSE

= FALSE

arvona on FALSE

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


Esimerkkejä

='Ms.'

tuloksena on kentät, joissa kentän sisältö on "Ms."

<'2001-01-10'

palauttaa päivät, jotka olivat ennen tammikuun 10. päivää 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-ohjausmerkkisarja: {escape 'ohjausmerkki'}

Esimerkki: SELECT * FROM Tuotteet WHERE tuoteNimi LIKE 'The *%' {escape '*'}

Esimerkki antaa tulokseksi kaikki merkinnät, joissa tuote alkaa 'The *'. Tämä tarkoittaa, että voidaan hakea myös merkeillä, jotka muuten tulkittaisiin paikkamerkeiksi, kuten *, ?, _, % tai piste.

Outer Join -ohjausmerkkisarja: {oj ulkoliitos}

Esimerkki: SELECT Tuotteet.* FROM {oj Tuotteet LEFT OUTER JOIN tilausRivit ON tuoteTunnus=tilausRivit.tuoteTunnus}

Tekstikenttien kysely

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

Päivämääräkenttien kysely

Päivämääräkentät esitetään merkinnällä #Päivämäärä#, jotta ne selvästi erottuvat päivämääriksi. Ehtolausekkeissa käytettävät päivämäärä-, kellonaika- ja aikaleimavakiot voivat olla joko SQL Escape -syntaksin mukaisia tai SQL2-syntaksin mukaisia.

Päivämäärätyyppi

SQL Escape -syntaksi #1 - voi olla vanhentunut

SQL Escape -syntaksi #2

SQL2-syntaksi

Päivämäärä

{D'YYYY-MM-DD'}

{d 'YYYY-MM-DD'}

'YYYY-MM-DD'

Aika

{D'HH:MM:SS'}

{t 'HH:MI:SS[.SS]'}

'HH:MI:SS[.SS]'

Aikaleima

{D'YYYY-MM-DD HH:MM:SS'}

{ts 'YYYY-MM-DD HH:MI:SS[.SS]'}

'YYYY-MM-DD HH:MI:SS[.SS]'


Esimerkki: SELECT {d '1999-12-31'} FROM world.years

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

Kysely Kyllä/Ei -kentissä

Kyseltäessä Kyllä/Ei-kentistä dBASE-tauluille käytetään oheista syntaksia:

Tila

Kyselyn ehto

Esimerkki

Kyllä

dBASE-tauluille: ei yhtä suuri kuin joku annetuista arvoista

=1 antaa tulokseksi kaikki tietueet, joissa Kyllä/Ei-kentässä on tilana "Kyllä" tai "Käytössä" (valittuna mustana),

Ei

.

=0 antaa tulokseksi kaikki tietueet, joissa Kyllä/Ei-kentässä on tilana "Ei" tai "Ei käytössä" (ei valittuna).

tyhjä

IS NULL

IS NULL antaa tulokseksi kaikki tietueet, joissa Kyllä/Ei-kentässä ei ole tilana Kyllä eikä Ei (valittuna harmaana)


Huomautus-kuvake

Syntaksi on käytetystä tietokannasta riippuva. Kyllä/Ei-kenttä voidaan myös määritellä eri tavalla (vain 2 tilaa 3 asemesta).


Parametrikyselyt

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

Varoitus-kuvake

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.


Vihje-kuvake

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.

Parametrin syöttö

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.

Vihje-kuvake

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

SQL on lyhenne sanoista "Structured Query Language" (rakenteellinen kyselykieli) ja se sisältää relaatiotietokantojen päivittämiseen ja hallinnointiin tarvittavat käskyt.

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.