Data Query Language DQL

Aggregate function:

SQL provides the following aggregate functions:

COUNT(*) Count the number of tuples
COUNT(<column name>) Count the values ​​in a column
SUM(<column name>) Find the sum of the values ​​of a column (the value of this column must be numeric)
AVG(<column name>) Find the average of a column (the value of this column must be numeric)
MAX(<column name>) find the maximum value of a column
MIN(<column name>) find the minimum value of a column

The complete structure of the SELECT statement:

SELECT <column name or column expression sequence of target table>

    FORM <base table name or/and view sequence>

    [ WHARE <line conditional expression>]

    [ GROUP BY <sequence of column names>

            [ HAVING <group conditional expression> ] ]

    [ORDER BY <列名[ ASC | DESC ]>, ... ]

The execution process of the entire statement is as follows:

  1. Read the data of the basic table and view in the FORM clause, and perform the Cartesian product operation;
  2. selects tuples that satisfy the conditional expression given in the WHERE clause;
  3. Group by the values ​​of the specified columns in the GROUP clause, while extracting those columns that satisfy the group condition expression in the HAVING clause;
  4. Evaluate the output by the column name or column expression given in the SELECT clause;
  5. The ORDER clause sorts the output target table, ASC means ascending order, DESC means descending order.

Regarding the SELECT clause:

The SELECT clause is used to describe the tabular structure of the query output. Its form is as follows:

SELECT [ ALL | DISTINCT ] <column name or sequence of column expressions> | *

  • The DISTINCT option ensures that duplicate rows will be removed from the result; ALL is the default value, meaning that duplicate rows remain in the result;
  • Asterisk * means select all columns;
  • A column expression means an expression that computes an aggregate value for a single column, that is, using the above aggregate function;
  • Arithmetic expressions of +, -, *, / and column names and constants are allowed in expressions.

Column and basic table renaming operations:

Use AS to rename columns and base tables. Sometimes a basic table appears in multiple SELECTs or the column names requested by the user are inconsistent with those in the basic table, so the basic table or column can be renamed.

SELECT SNAME AS STUDENT_NAME
FORM S AS STUDENT

Union, intersection, and difference operations of sets:

When the structures of the two subqueries are exactly the same, operations such as union, intersection, and difference can be performed on the two subqueries. The operators for union, intersection and difference are: UNION, INTERSECT, EXCEPT. If the three keywords are followed by ALL, the duplicate tuples will not be eliminated. Without ALL, the returned result will eliminate the duplicated tuples.

(SELECT query statement 1)

UNION [ ALL ]

(SELECT query statement 2)

(SELECT query statement 1)

INTERSECT [ ALL ]

(SELECT query statement 2)

(SELECT query statement 1)

EXCEPT [ ALL ]

(SELECT query statement 2)

The above operations without the keyword ALL will eliminate duplicate tuples in the returned result; with ALL, duplicate tuples will not be eliminated.

Regarding the WHERE clause:

The following operators can be used in the conditional expression F in the WHERE clause:

  • Arithmetic comparison operators: <, <=, >, >=, =, <> or ! =
  • Logical operators: AND, OR, NOT
  • Set membership operators: IN, NOT IN
  • 谓词:EXISTS, ALL, SOME, UNIQUE
  • Aggregate functions: AVG, MIN, MAX, SUM, COUNT 
  • Interval judgment: [NOT] BETWEEN ... TO ...
  • Equivalent judgment: [NOT] LIKE
  • Null value judgment: IS [NOT] NULL
  • The operand in F can also be another SELECT statement, that is, SELECT can be nested.

String matching operations:

The string matching operator is "LIKE", and two wildcards can be used in expressions:

  • Percent sign: matches a string of zero or more characters;
  • Underscore: Matches a single character.
//匹配S中以字母D打头的学生姓名SELECT SNAME
    FORM S
    WHERE SNAME LIKE'D%';

To make strings contain special characters (% and _), SQL allows to define escape characters. An escape character is placed immediately before a special character, indicating that the special character is to be treated as a normal character. Use the ESCAPE keyword in LIKE to define escape characters.

LIKE 'ab\%cd%' ESCAPE'\'    //匹配所有以ab%cd开头的字符串

SQL also allows a variety of functions to be used on characters, such as concatenation ("||"), extracting substrings, calculating the length of strings, converting upper and lower cases, etc.

Comparison operations for null values:

SQL allows the column value to be empty, the empty value is represented by NULL, and NULL does not occupy space.

The existence of null values ​​increases the complexity of arithmetic and comparison operations. SQL stipulates that when one of the arithmetic expressions involving +, -, *, / is a null value, the value of the expression is also a null value. The result of comparison operations involving null values ​​is considered "false".

When a null value is encountered in an aggregate function, except for COUNT(*), the null value is skipped to handle the non-null value.

Comparison of set membership:

The operation of determining whether a tuple is in the result of a query (i.e. a set) is called a "comparison of set membership". Its form is:

<tuple> [NOT] IN (<set>)

Tuples and sets should be in the same form here. The IN operator says to return true if the hike is inside the set.

//在S和SC中检索至少不学C2和C4两门课的学生学号SELECT S#
FORM SWHERE S# NOT IN (SELECT S#
                 FORM SC
                 WHERE C# IN ('C2','C4'));

Comparison of set member arithmetic:

Its form is as follows:

<tuple> θ  ALL | SOME | ANY (<set>)

θ is an arithmetic comparison operator "θ ALL" indicates that the tuple on the left and each tuple in the right set satisfy the θ operation; "θ SOME" and "θ ANY" have the same meaning, indicating that the tuple on the left and at least one of the right set Tuples satisfy theta operation.

It should be noted here that the comparison of tuples is similar to that of strings. E.g:

(a1, a2) = (b1, b2), which means (a1<b1) OR (a1=b1) AND (a2<=b2)

Test for existence of duplicate tuples in a collection:

SELECT T#, TNAME
FORM TWHERE UNIQUE (SELECT T#
              FORM C
              WHERE C.T# = T.T#);

Improved Writing of Nested Query

Use of export tables

SQL statements allow subqueries to be used in FORM. If a subquery is used in FROM, a table name and corresponding column name should be given for the result of the query.

//在基本表SC中检索平均成绩最高的学生学号
SELECT SC.S#
FROM SC,(SELECT AVG(SCORE)
         FROM SC
         GROUP BY S#) AS RESULT(AVG_SCORE)
GROUP BY SC.S#
     HAVING AVG(SC.SCORE)>=ALL(RESULT.AVG_SCORE);

Temporary view of WITH clause

SQL allows users to define a temporary view (ie, a subquery) with the WITH statement, placed at the beginning of the SELECT statement. The temporary view itself is defined with a SELECT statement.

WITH RESULT(AVG_SCORE)AS
    SELECT AVG(SCORE)
    FROM SC
    GROUP BY S#
SELECT S#
FROM SC.RESULT
GROUP BY S#
    HAVING AVG(SCORE)>=ALL(RESULT.AVG_SCORE);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325060662&siteId=291194637