Päringu koostamine

Päringu koostamisvaade võimaldab luua ja redigeerida andmebaasi päringuid.

Selle käsu kasutamiseks...

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


Märkuse ikoon

Enamikus andmebaasides kasutatakse päringuid andmebaasi tabelite filtreerimiseks või sortimiseks, et kuvada kirjeid arvutis. Vaated pakuvad samu funktsioone nagu päringudki, kuid serveri poolel. Kui sinu andmebaas asub vaateid toetavas serveris, võid serveris olevate kirjete filtreerimiseks kasutada vaateid, kiirendades nii kuvamist.


Märkuse ikoon

Valides andmebaasi kaardilt Tabelid käsu Loo vaade, avatakse aken Vaate koostamine, mis sarnaneb siin kirjeldatud aknaga Päringu koostamine.


Päringu koostamise akna paigutus talletatakse loodud päringus, kuid seda ei saa talletada loodud vaates.

Koostamisvaade

Päringu loomiseks klõpsa andmebaasidokumendis ikooni Päringud ja seejärel Loo päring koostamisvaates.

Koostamisvaate alaosa on mõeldud päringu kirjeldamiseks. Päringu kirjeldamiseks on vaja määrata päringusse kaasatavad andmebaasi väljade nimed ja väljade kuvamise kriteeriumid. Koostamisvaate alaosas olevate veergude järjestuse muutmiseks lohista veeru päis uude kohta või vali veerg ja kasuta klahvikombinatsiooni +nooleklahv.

Koostamisvaate akna ülaääres kuvatakse päringu koostamise riba ja koostamise riba ikoone.

Kui soovid päringut testida, siis tee andmebaasidokumendi päringu nime peal topeltklõps. Päringu tulemust näidatakse andmeallikavaate sarnases tabelis. Märkus: näidatav tabel on vaid ajutine.

Klahvid päringu koostamisvaates

Klahv

Funktsioon

F4

Eelvaade

F5

Käivitab päringu

F7

Lisab tabeli või päringu


Lehitse

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.

Väljade lisamiseks päringusse, tee neil topeltklõps. Relatsioonide defineerimiseks lohista välju.

Märkuse ikoon

Päringu koostamise ajal ei saa valitud tabeleid muuta.


Eemalda tabelid

Tabeli eemaldamiseks koostamisvaatest klõpsa tabeli ülaäärisel, ava kontekstimenüü ja vali käsk Kustuta. Teiseks võimaluseks on vajutada klahvi Delete.

Liiguta tabelit ja muuda tabeli suurust

Tabeleid on võimalik vastavalt oma eelistustele ümber korraldada ja nende suurust muuta. Tabeli liigutamiseks lohista see hiirekursori abil ülemisest äärest kinni hoides soovitud kohale. Tabeli suurendamiseks või vähendamiseks aseta hiirekursor tabeli äärisele või nurgale ja lohista see kuni soovitud suuruseni.

Tabeli relatsioonid

Kui kahe tabeli väljade vahel on mingi relatsioon, siis saab seda päringus kasutada.

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.

Mitmeid tabelitevahelisi relatsioone sisaldavaid päringuid on võimalik luua vaid LibreOffice'i andmebaasiliidest kasutades.

Märkuse ikoon

Sa ei saa kasutada päringus erinevate andmebaaside tabeleid. Mitut tabelit hõlmavat päringut saab luua vaid ühe andmebaasi piires.


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.

Teiseks võimaluseks on vajutada tabeldusklahvi, kuni valitakse soovitud ühenduse joon (kuvatakse suurendatult), vajutada seejärel kontekstimenüü avamiseks Shift+F10 ja valida käsk Redigeeri. Mõned andmebaasid toetavad ainult teatud ühenduste tüüpe.

Relatsioonide kustutamine

Tabelitevahelise relatsiooni kustutamiseks klõpsa neid ühendaval joonel ning vajuta Delete klahvi.

Teiseks võimaluseks on kustutada vastavaid kirjeid dialoogi Relatsioonid sektsioonis Asjassepuutuvad väljad või vajutada tabeldusklahvi, kuni aktiveeritakse õige ühendusjoon, vajutada kontekstimenüü avamiseks Shift+F10 ja valida sealt käsk Kustuta.

Defining the query

Vali päringu defineerimiseks vajalikud tingimused. Iga koostamise aluseks oleva tabeli veerg vastab ühele päringu andmeväljale. Ühes reas olevad tingimused ühendatakse loogilise JA-tehte abil.

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.

Väljanimede kustutamine

Välja eemaldamiseks päringust klõpsa vastava veeru päises ning vali veeru kontekstimenüüst Kustuta.

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.

Skeem

Sisesta skeemi nimi, mis omistatakse päringule või tabeli vaatele.

Päringu või tabeli vaate nimi

Sisesta päringu või tabeli vaate nimi.

Andmete filtreerimine

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

Väli

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.

Alias

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 veerg AS alias FROM tabel.

Näiteks:

SELECT "VoNr" AS "VaruosaNr" FROM "Varuosad"

Tabel

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.

Sordi

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ähtav

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.

Kriteeriumid

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

või

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:

Funktsioonid

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:

Valik

SQL

Efekt

Funktsioon puudub

Ühtegi funktsiooni ei täideta.

Keskmine

AVG

Arvutab veeru aritmeetilise keskmise.

Arv

COUNT

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

a) COUNT(*): Määrates argumendiks tärni, loendab kokku kõik tabeli kirjed.

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.

Maksimum

MAX

Determines the highest value of a record for that field.

Miinimum

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.

Rühmitamine

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.


Funktsioone on võimalik ka otse SQL-lauses välja kutsuda. Süntaks on:

SELECT FUNKTSIOON(veerg) FROM tabel.

Näiteks summa arvutamise funktsiooni väljakutsumine SQL-käsus on järgmine:

SELECT SUM("Hind") FROM "Artikkel".

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.

Vastav funktsioon SQL lauses on:

SELECT FUNCTION() AS alias FROM tabel

Näide:

SELECT COUNT(*) AS count FROM "Artikkel"

Märkuse ikoon

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


Näited

Järgnevas näites käivitatakse päring üle kahe tabeli: tabel "Kaup", milles on väli "Kauba_Nr" ja tabel "Tarnija", milles on väli "Tarnija_Nimi". Lisaks on mõlemas tabelis ühine väli "Tarnija_Nr".

Selleks, et luua päring, mis sisaldab kõiki varustajaid, kes tarnivad rohkem kui kolme kaupa, peab läbima järgmised sammud.

  1. Lisa päringu koostamisse tabelid "Kaup" ja "Tarnija".

  2. Seosta omavahel kahe tabeli "Tarnija_Nr" väljad, kui sellist seost veel ei ole.

  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. Sisesta kriteeriumiks >3 ning keela väli Nähtav.

  5. Tabelis "Tarnija" tee topelklõps väljal "Tarnija_Nimi" ning vali funktsioon Group.

  6. Käivita päring.

Kui tabelis "Kaup" on olemas väljad "Hind" (iga artikli konkreetne hind) ning "Tarnija_Nr" (vastava artikli tarnija), siis võid saada artikli keskmise hinna varustaja kohta järgmise päringuga:

  1. Lisa tabel "Kaup" päringu koostamisse.

  2. Tee väljadel "Hind" ja "Tarnija_Nr" topeltklõps.

  3. Luba rida Funktsioon ja vali väljal "Hind" funktsioon "Keskmine".

  4. Sõna "Keskmine" (ilma jutumärkideta) võid sisestada ka aliase nime reale.

  5. Vali välja "Tarnija_Nr" jaoks funktsioon Rühmitamine.

  6. Käivita päring.

Kontekstimenüüs on saadaval järgnevad käsud ja sümbolid:

Funktsioonid

Shows or hides a row for the selection of functions.

Tabeli nimi

Näitab või peidab rea, kus on tabeli nimi.

Aliase nimi

Näitab või peidab rea, kus on aliase nimi.

Erinevad väärtused

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

Näiteks juhul kui aadressiandmebaasis esineb nimi "Sepp" mitu korda, võid valida käsu Erinevad väärtused määramaks, et nimi "Sepp" kuvatakse vaid ühe korra.

Mitut välja hõlmava päringu korral peab kõigil väljadel olevate väärtuste kombinatsioon olema ainulaadne, et konkreetsete kirjete põhjal saaks tulemuse tagastada. Oletame näiteks, et aadressiraamatus esineb ühel korral "Sepp Tallinnas" ja kahel korral "Sepp Tartus". Käsu Erinevad väärtused rakendamisel kasutatakse päringus kahte välja – "perekonnanimi" ja "linn" – ning tulemusena tagastatakse "Sepp Tallinnas" ühel korral ja "Sepp Tartus" ühel korral.

SQL-is vastab see käsk predikaadile DISTINCT.

Piirväärtus

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.

Filtreerimistingimuste formuleerimine

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:

Operaator

Tähendus

Tingimus on täidetud kui...

=

võrdne

... välja sisu on näidatud avaldisega identne.

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

<>

mittevõrdne

... välja sisu ei võrdu näidatud avaldisega.

>

suurem kui

... välja sisu on suurem kui näidatud avaldis.

<

väiksem kui

... välja sisu on väiksem kui näidatud avaldis.

>=

suurem või võrdne

... välja sisu on näidatud avaldisest suurem või võrdne.

<=

väiksem või võrdne

... välja sisu on näidatud avaldisest väiksem või võrdne.


LibreOffice'i käsk

SQL käsk

Tähendus

Tingimus on täidetud kui...

IS EMPTY

IS NULL

on 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

ei ole tühi

... 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 element üksuses

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

Pole element üksuses

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

BETWEEN x AND y

BETWEEN x AND y

jääb vahemikku [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 jää vahemikku [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...)

sisaldab 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 sisalda a, b, c...

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

= TRUE

= TRUE

omab väärtust Tõene

... välja nimi omab väärtust Tõene.

= FALSE

= FALSE

omab väärtust väär

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


Näited

='Ms.'

tagastab väljade nimed, mille välja sisu on "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 Paojada: {pagu 'paomärk'}

Näide: select * from Kaup where KaubaNimi like 'Kaup *%' {pagu '*'}

Selle näite korral leitakse kõik kirjed, kus kauba nime algus on kujul "Kaup *". See tähendab, et on võimalik otsida ka selliseid märke, mida muidu oleks peetud metamärkideks (nt *, ?, _, % või punkt).

Väline ühendus Paojada: {oj outer-join}

Näide: select Artikkel.* from {oj kaup LEFT OUTER JOIN tellimused ON kaup.no=tellimused.ANR}

Päringud tekstiväljadele

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ärigud kuupäeva väljades

Selleks et kuupäevavälju selgelt kuupäevana tuvastada tähistatakse need järgmiselt: #Date#. Kuupäevatingimus esitatakse SQL-lauses järgmisel ODBC-ga ühilduval moel:

Date Type Element

SQL Escape syntax #1 - may be obsolete

SQL Escape syntax #2

SQL2 syntax

Kuupäev

{D'YYYY-MM-DD'}

{d 'YYYY-MM-DD'}

'YYYY-MM-DD'

Kellaaeg

{D'HH:MM:SS'}

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

'HH:MI:SS[.SS]'

Kuupäev-kellaaeg

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

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

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


Näide: select {d '1999-12-31'} from maailm.aastad

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

Päringud Jah/Ei väljades

dBASE'i puhul kasuta tabeli Jah/Ei väljadele päringu koostamisel järgmist süntaksit:

Olek

Päringu kriteerium

Näide

Jah

dBASE'i tabelite jaoks: mittevõrdne ühegi antud väärtusega

=1 tagastab kõik kirjed, kus Jah/Ei väli omab väärtust "Jah" või "Sees" (märgitud mustana)

Ei

.

=0 tagastab kõik kirjed, kus Jah/Ei väli omab väärtust "Ei" või "Väljas" (märgistust pole)

Null

IS NULL

IS NULL tagastab kõik kirjed, kus Jah/Ei väli ei ole Jah ega Ei (märgitud hallina)


Märkuse ikoon

Süntaks sõltub kasutatava andmebaasi tüübist. Pane tähele, et Jah/Ei-väljad võivad olla ka teistmoodi määratletud (ainult 2 olekut 3 asemel).


Parameetri päringud

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

Hoiatav ikoon

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.


Nõuande ikoon

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.

Parameetri sisestamine

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.

Nõuande ikoon

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-režiim

SQL on lühend sõnadest "Stuctured Query Language" ja kirjeldab käske relatsiooniliste andmebaaside värskendamiseks ning administreerimiseks.

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.

Palun toeta meid!