SQLite study notes (b)

Disclaimer: This article is a blogger original article, please indicate the source: https://blog.csdn.net/qq_38182125/article/details/89409578

Outline

The ultimate goal of the design of the database and create a table is to use the data. Together with the database work is work and SQL data manipulation language (DML). DML is the core of the SELECT command, it is also the only command queries the database. The paper is organized as follows:

  • The general form of the SELECT command
  • FROM keyword description
  • WHERE keyword description
  • ORDER BY keyword description
  • LIMIT & OFFSET keyword description
  • GROUP BY & HAVING keyword description
  • DISTINCT keyword description

Ready to work:

In the text, we will in the following table Products, for example, as shown in the following table:
Here Insert Picture Description
you can see, there are 9 Products table rows of data. View this table composed by .schema command:

sqlite> .schema Products
CREATE TABLE Products
(
  prod_id    char(10)      NOT NULL ,
  vend_id    char(10)      NOT NULL ,
  prod_name  char(255)     NOT NULL ,
  prod_price decimal(8,2)  NOT NULL ,
  prod_desc  text          NULL     ,
  PRIMARY KEY (prod_id)             ,
  FOREIGN KEY (vend_id) REFERENCES Vendors (vend_id)
);

After know the composition and the data of this table, then we have to learn the SELECT command.

SELECT command

The general form of the SELECT command follows:

SELECT [DISTINCT] heading
FROM tables
WHERE predicate
GROUP BY columns
HAVING predicate
ORDER BY columns
LIMIT offset,count;

Wherein capital in August for the SELECT command keywords, this is the SELECT command is the most complete form of expression, but not every part is necessary. The most common SELECT clause as follows:

SELECT heading FROM tables WHERE predicate;

We are going to analyze the above SELECT command through the dismantling of the way.


1. FROM

FROM keyword indicates the table from which to retrieve the data, if it contains more than one table, then between the tables separated by commas, it will be combined into one single relationship between multiple tables. Examples are as follows:

Input:

SELECT prod_id, prod_name, prod_price FROM Products;

Output:

prod_id     prod_name          prod_price
----------  -----------------  ----------
BR01        8 inch teddy bear  5.99
BR02        12 inch teddy bea  8.99
BR03        18 inch teddy bea  11.99
BNBG01      Fish bean bag toy  3.49
BNBG02      Bird bean bag toy  3.49
BNBG03      Rabbit bean bag t  3.49
RGAN01      Raggedy Ann        4.99
RYL01       King doll          9.49
RYL02       Queen doll         9.49

2. WHERE

WHERE keyword to filter data, the prediction logic WHERE parameter is easiest prediction is asserted, as follows:

Input:

SELECT prod_name, prod_price 
FROM Products 
WHERE prod_price = 3.49; 

Output:

prod_name          prod_price
-----------------  ----------
Fish bean bag toy  3.49
Bird bean bag toy  3.49
Rabbit bean bag t  3.49

This SELECT command line only the prod_price 3.49 to print out. In addition to assertion may be used to filter operator, SQLite operator support is located at the end of the text. Next, using an operator filtered show several examples:

Mismatch checks

Input:

SELECT vend_id, prod_name
FROM Products
WHERE vend_id <> 'DLL01';

Output:

vend_id     prod_name
----------  -----------------
BRS01       8 inch teddy bear
BRS01       12 inch teddy bea
BRS01       18 inch teddy bea
FNG01       King doll
FNG01       Queen doll

You can see the output filtered out of line vend_id to DLL01.

Range check

Input:

SELECT prod_name, prod_price 
FROM Products 
WHERE prod_price BETWEEN 5 AND 10;

Output:

prod_name          prod_price
-----------------  ----------
8 inch teddy bear  5.99
12 inch teddy bea  8.99
King doll          9.49
Queen doll         9.49

Here we prod_price the filtered data between 5 to 10 (including 5 and 10), and an AND BETWEEN uses keywords.

A plurality of AND or OR operation

WHERE allow any number of a plurality of AND or OR operator, but when using the AND operator pay special attention to the higher priority than OR, otherwise can be error prone. For example, we want to filter out the Products table vend_id line 10 is equal to or BRS01 DLL01 prod_price value greater than, if we enter the following:

SELECT vend_id, prod_price 
FROM Products 
WHERE vend_id= 'DLL01' OR vend_id= 'BRS01' 
AND prod_price >= 10;

Output:

vend_id     prod_price
----------  ----------
BRS01       11.99
DLL01       3.49
DLL01       3.49
DLL01       3.49
DLL01       4.99

You can see there are prod_price output of less than 10 lines, so this output is not what we expected output, causing the main reason for this priority is higher than AND OR. Therefore, the correct input should be:

SELECT vend_id, prod_price 
FROM Products 
WHERE (vend_id= 'DLL01' OR vend_id= 'BRS01') 
AND prod_price >= 10;

Output:

vend_id     prod_price
----------  ----------
BRS01       11.99

By parentheses, then the output is the result of what we want.

IN operator

IN operator to specify a range of conditions, in the range of each condition can be matched. IN take a set separated by a comma, enclosed in parentheses legal values.
Input:

SELECT prod_name, prod_price 
FROM Products 
WHERE vend_id IN('DLL01', 'BRS01');

Output:

prod_name          prod_price
-----------------  ----------
8 inch teddy bear  5.99
12 inch teddy bea  8.99
18 inch teddy bea  11.99
Fish bean bag toy  3.49
Bird bean bag toy  3.49
Rabbit bean bag t  3.49
Raggedy Ann        4.99
LIKE operator

Input:

SELECT prod_name, prod_price 
FROM Products 
WHERE prod_name LIKE '%inch%';

Output:

prod_name          prod_price
-----------------  ----------
8 inch teddy bear  5.99
12 inch teddy bea  8.99
18 inch teddy bea  11.99

LIKE affinity match, the percent sign (%) represents any number from 0 to match any character, i.e. matching greedy; in addition to underscore (_) indicates match any one character. And through which we can easily filter out content matching substring. Note that the LIKE matching is not case-sensitive, which means that '%inch%'the '%INCH%'match result is the same.

GLOB operator

Input:

SELECT prod_name, prod_price 
FROM Products 
WHERE prod_name GLOB '1*';

Output:

prod_name           prod_price
------------------  ----------
12 inch teddy bear  8.99
18 inch teddy bear  11.99

GLOB and LIKE role is very similar, the key difference is that it uses some file name like UNIX / Linux replacement syntax. That it uses * _ or to matching, and matching GLOB is case sensitive. Note that the LIKE and GLOB can only match the string, other types of values ​​that can not be matched!


3. ORDER BY

ORDER BY keywords are retrieved for data sorting, the following example shows:

Input:

SELECT prod_name
FROM Products;

Output:

prod_name
-----------------
8 inch teddy bear
12 inch teddy bea
18 inch teddy bea
Fish bean bag toy
Bird bean bag toy
Rabbit bean bag t
Raggedy Ann
King doll
Queen doll

It can be seen that the output appears to be disordered, it is generally added to the original data in accordance with the order shown in the table. If we need to sort the output, we can add the ORDER BY keyword, as follows:

Input:

SELECT prod_name 
FROM Products
ORDER BY prod_name;

Output:

prod_name
------------------
12 inch teddy bear
18 inch teddy bear
8 inch teddy bear
Bird bean bag toy
Fish bean bag toy
King doll
Queen doll
Rabbit bean bag to
Raggedy Ann

The default output is arranged in ascending order, if arranged in descending order, can be coupled with the back of DESC keywords, such as the above example are sorted in descending order can be written:

SELECT prod_name 
FROM Products
ORDER BY prod_name DESC;

If you need to sort by multiple fields, for example in the press prod_price Products sorting, and then sorted by PROD_NAME, inputs can be written as:

SELECT prod_id, prod_price, prod_name 
FROM Products 
ORDER BY prod_price, prod_name;

Output:

prod_id     prod_price  prod_name
----------  ----------  -----------------
BNBG02      3.49        Bird bean bag toy
BNBG01      3.49        Fish bean bag toy
BNBG03      3.49        Rabbit bean bag t
RGAN01      4.99        Raggedy Ann
BR01        5.99        8 inch teddy bear
BR02        8.99        12 inch teddy bea
RYL01       9.49        King doll
RYL02       9.49        Queen doll
BR03        11.99       18 inch teddy bea

The SQL also supports sorting by the relative position of the field, so the above SQL statement can also be written as:

SELECT prod_id, prod_price, prod_name 
FROM Products 
ORDER BY 2,3;

2 and 3 refer to the distribution is prod_price and prod_name.


4. LIMIT & OFFSET

LIMIT and OFFSET keyword for defining the size and scope of the result set. LIMIT specifies the maximum number of records returned, OFFSET offset amount of the specified record. Examples are as follows:

Input:

SELECT prod_name, prod_price 
FROM Products 
ORDER BY prod_price, prod_name 
LIMIT 5 OFFSET 0;

Output:

prod_name          prod_price
-----------------  ----------
Bird bean bag toy  3.49
Fish bean bag toy  3.49
Rabbit bean bag t  3.49
Raggedy Ann        4.99
8 inch teddy bear  5.99

Wherein when OFFSET is 0, OFFSET 0 omitted. Data can be seen that the first 5 now shows the sorted data, to view the subsequent data, the offset +5 directly, as shown below:

SELECT prod_name, prod_price 
FROM Products 
ORDER BY prod_price, prod_name 
LIMIT 5 OFFSET 5;

Output:

prod_name           prod_price
------------------  ----------
12 inch teddy bear  8.99
King doll           9.49
Queen doll          9.49
18 inch teddy bear  11.99

And when used together and OFFSET LIMIT, OFFSET keyword may be replaced with a comma, the above example can be written as:

SELECT prod_name, prod_price 
FROM Products 
ORDER BY prod_price, prod_name 
LIMIT 5, 5;

Where the first number represents the offset, the second number represents the size of the result set.


5. GROUP BY & HAVING

GROUP BY and HAVING keyword is used to group the data. Before learning group we start to understand a function count. This function is used to determine the number of rows in the table, for example, the following command returns the number of rows in the Products table:

SELECT COUNT(*) 
FROM Products;

Output:

COUNT(*)
----------
9

Products described has nine rows of data. After an overview of this function, we continue to return to the topic in this section. First, explain the significance of packets where?

First, suppose a scene in the Products table, represents the value of vend_id product suppliers, the number of products at this time if we want to return to the supplier DLL01 provided, you can easily write the following command:

SELECT COUNT(*) 
FROM Products
WHERE vend_id='DLL01';

But if we want to return the number of products each vendor, or to return to provide more than two suppliers of products, this time in accordance with the previous way we seem unable to do so, then we need to use the grouping.

One problem : Returns the number of products each vendor, we can do this:

Input:

SELECT vend_id, COUNT(*) 
FROM Products 
GROUP BY vend_id;

Output:

vend_id     COUNT(*)
----------  ----------
BRS01       3
DLL01       4
FNG01       2

It can be seen after the use of GROUP BY, it indicates DBMS sorted by vend_id and packet data. This will each vend_id instead of the entire table to calculate the number of products. As can be seen from the output results of suppliers BRS01 has three products, DLL01 has four products, FNG01 has two products.

Second problem : Return suppliers to provide two or more products.

Previously used GROUP BY allows us to vend_id that is, suppliers are grouped, then how to filter these vendors do? It is necessary to use the HAVING keyword, we can use the following command:

SELECT vend_id 
FROM Products 
GROUP BY vend_id 
HAVING COUNT(*) > 2;

Output:

vend_id
----------
BRS01
DLL01

We can see the success of filtering out the name of the supplier to provide quantities greater than 2 products.

HAVING and WHERE usage is very similar. WHERE almost all the technology and options apply to HAVING. The key difference between them is that the filtered packets HAVING WHERE filter is a row.

In question two, we can know WHERE does not work here, because the filter is grouped, so we use the HAVING.

In addition, when the WHERE and HAVING used simultaneously, there is little need to pay particular attention to:

WHERE filtered before data packets, HAVING filtered after the data packet. Therefore WHERE excluding lines included in the packet.

On this point we see the following three questions.

Question three : List with two or more products and their prices greater than or equal Supplier 4:

SELECT vend_id, COUNT(*) 
FROM Products 
WHERE prod_price >= 4 
GROUP BY vend_id 
HAVING COUNT(*) > 2;

Output:

vend_id     COUNT(*)
----------  ----------
BRS01       3

From the results it can be seen the number of rows before the packet is first filtered sub statement WHERE, again filtered line grouping, then filtered vend_id HAVING meet the conditions.


6. DISTINCT

Finally, we say it DISTINCT keyword. This keyword is used to remove duplication. When this statement keyword, if the result of the SELECT duplicate, then it will filter out which duplicate rows. Examples are as follows:

Input:

SELECT DISTINCT vend_id 
FROM Products;

Output:

vend_id
----------
BRS01
DLL01
FNG01

As can be seen from the output, filtered and the vend_id duplicate rows, so that the original line 3 into a line 9.


So far, the SELECT command on keywords that appear on the finished presentation. Finally, attach the SELECT SQLite a processing procedure as summarized above in FIG:
SQLite SELECT processing procedure in FIG.


Finally, attach the WHERE keyword may be used in the operator:

Operators Types of effect
|| String connection
* Arithmetic Multiply
/ Arithmetic except
% Arithmetic I
+ Arithmetic plus
- Arithmetic Less
<< Bitwise The left
>> Bitwise Right
& Logical versus
| Logical or
< Relational Less than
<= Relational Less than or equal
> Relational more than the
>= Relational greater or equal to
= Relational equal
== Relational equal
<> Relational not equal to
!= Relational not equal to
IN Logical In
AND Logical versus
OR Logical or
IS Logical Equal equal
LIKE Relational St String match
GLOBE Relational Fi File name matches

reference

"SQLite Definitive Guide"

  • Chapter 3 sqlite in sql

"SQL must know will be"

  • Lesson 2 Retrieving data
  • Sort retrieve data Lesson 3
  • Lesson 4 filtered data
  • Lesson 5 Advanced Filtering data
  • Lesson 6 filtered with a wildcard
  • Data packet 10 Lesson

Figure articles, tables etc from "SQLite Definitive Guide", all from the examples of "SQL must know will be", please indicate the source!


I hope this article to help you ~

Guess you like

Origin blog.csdn.net/qq_38182125/article/details/89409578