04 table record query

04 table record query

DQL: Data Query Language

[] ---> means optional <> ---> means mandatory | ---> optional

1. Generalization

1. Query can not only realize data retrieval, but also calculate and merge data from different data sources during the query process

2. Query by select statement is the only way to retrieve information in the database, and it is the most frequently used statement in SQL statements

  • Start the server: net start mysql (run as an administrator)

  • Shut down the server: net stop mysql

  • Log in to the MySQL server: mysql -u login account -p

  • Disconnect the server: quit

  • Show all database names: show databases;

  • Use the database: use database name;

  • Display the name of the table in the current database: show tables;

  • Display table structure: desc table name;

 

2. Statement format:

  • SELECT [ALL | DISTINCT] <target column expression> [,<target column expression>]

  • FROM <table name or view name>[, <table name or view name>]

  • [ WHERE <conditional expression>]

  • [ GROUP BY <column name 1> [ HAVING <conditional expression>]]

  • [ ORDER BY <列名2> [ ASC | DESC ] ];

 

3. Brief introduction:

  • SELECT clause: specify the attribute column to be displayed

  • FROM clause: Specify the query object (basic table or view)

  • WHERE clause: Specify query conditions

  • GROUP BY clause: group the query results according to the value of the specified column, and the tuples with the same attribute column value are a group. Usually aggregate functions are applied in each group.

  • HAVING phrase: filter out only groups that meet the specified conditions

  • ORDER BY clause: sort the query result table in ascending or descending order according to the specified column value

 

Fourth, the specific operation of table query:

  • Query column: select column name 1 [as alias], column name 2 [as alias] .. from table name

  • Query the information of all fields in the table: select * from table name (* is a wildcard)

  • Query the specified field information in the table:

    select field name from table name where query conditions;

  • Remove duplicate rows in the query results:

    select distinct field name from table name;

  • Query certain rows of data in the table:

    select field name from table name limit [start] ,length

    start means to start retrieval from the first row of records, the default is 0

    length indicates how many rows of records to retrieve

    Put it after the query statement

  • WHERE clause to set filter conditions

    1. Point out the query range: expression [NOT] between expression1 and expression2

      Note: expression1 cannot be greater than the value of expression2

      between contains the boundary value, not between does not contain the boundary value

    2. Specify a set: expression IN (expression....)

      All possible values ​​are listed in the value table. When the expression matches any value in the set, it returns true, otherwise it returns false

    3. Fuzzy query, character matching like: field name [NOT] like ...

      If the condition is uncertain, you must use the LIKE keyword for fuzzy query

      Use like for string matching, call the string a matching string, and compare it with the attribute value,

      The wildcard in the matching string is: _ any single character;% zero or more arbitrary strings

    4. Escaping: _ is transferred to _; \\ is transferred to\; \ is transferred to %;

    5. Null value query: is null; is not null means not empty

    6. Logical operators: AND (connect two conditions and return only when the conditions are true); OR (connect two conditions and return only if any one of the conditions is true); NOT (negate a condition and return only if the condition is not true) )

      Note: When there are multiple logical operators in the statement: first NOT, then AND, and finally OR

  • Sort in the query statement: select field name form table name order by field name 1 [ASC (ascending), DESC (descending)]

    The queried records are sorted according to the field name 1.

    The default sorting is ascending, that is, ASC is used by default; if sorting is in descending order, it must be changed to DESC

  • Sort multiple rows in the query statement:

    select field name form table name order by field name 1, field name 2... [ASC (ascending), DESC (descending)]

    The system will sort according to the first field in the order by clause, and when the field has the same value, it will sort according to the second field name, and so on

  • Group query results: select field name from table name group by <group by> [having <conditional expression extracted from group>]

    Note: HAVING <conditional expression>: The object is the group, that is, the grouped records are filtered

  • Concatenate the concentrated strings: group_concat (the field names that need to be displayed in a centralized manner, the simple point is the field names that need to be displayed on a line) function

Five, aggregate function

Aggregate functions often used in <target column expression>:
Count([distinct|all]*) count the number of tuples
Count([distinct|all]<column name>) count the number of values ​​in a column
sum([distinct|all]<column name>) Find the sum of a column of values
avg([distinct|all]<column name>) find the average value of a column of values
max([distinct|all]<column name>) Find the maximum value in a list of values
min([distinct|all]<column name>) Find the minimum value in a column of values
Distinct: Indicates that the duplicate values ​​in the specified column should be cancelled during calculation.
All: The default value, do not cancel the repeated value.
The above functions, except count(*), all other functions ignore the null value.
note:
    group_concat() function-concatenate the strings in the collection; you can also concatenate according to grouping fields, separated by commas
    Summarize records in the aggregate function: group by with rollup in group by

Multi-table query

DQL: Data Query Language

1. Concept

A query involving multiple tables at the same time is called a join query

The conditions used to connect two tables are called join conditions or join predicates

General format: [<table name1>.] <column name1> <comparison operator> [<table name2>.]<column name2>

Comparison operators: =, >, <, >=, <=, !=

The column name in the join predicate is the join field

The connection field types in the connection conditions must be comparable, but not necessarily the same

Second, the classification of the connection query

  • Classified according to the operator of the connection:

    1. Equivalent connection

    2. Non-equivalent join

  • Classified by connection type

    1. Internal connection

    2. Outer join

    3. Cross connect

Three, the representation method of the connection query

Put the connection condition after the from clause, the basic format is:

from R {connection type} join S {on condition} where {condition}

Connection Type:

  • Cross connection (Cartesian product)

  • inner: inner connection

  • left outer join: left outer join

  • right outer join: right outer join

  • full outer join: full outer join

Four, internal connection

Inner join, only return tuples matching the join condition

In the inner join, the tables participating in the join are equal, and the records that meet the conditions will be extracted from the two tables and combined into a new record

The basic format of inner connection:

  • Format 1: select field name from table 1 [inner] join table 2 join conditions

  • Format 2: select field name from table 1, table 2 where join conditions

note:

  • In multi-table query, when referring to the attribute with the same name in any clause, the table name prefix must be added, and the table name prefix can be added or omitted when the unique attribute name is quoted

  • The alias of the table can be used. Once the alias is used to replace a certain table name, the alias of the table must be used when querying, and the original name of the table can no longer be used

Five, conditional conversion-CASE function

CASE function is divided into simple case function and search case function

Simple case function -only data matching, no comparison operations and logical operations

Basic format:

CASE field name 
    WHEN value 1 THEN conversion value 1 
    WHEN value 2 THEN conversion value 2  
    ELSE conversion value n  
    END

Search case function -can complete more complex data conversion

The difference with the simple case function:

  • No field name after searching CASE

  • Boolean expression after WHEN

Basic format:

CASE
    WHEN Boolean expression 1 THEN conversion value 1
    WHEN Boolean expression 2 THEN conversion value 2
    ELSE conversion value n
    END

Six, external connection

Outer join-not only returns records that match the join condition, but also returns records that do not match the join condition according to the different types of outer joins

  • Left outer join

  • Right outer join

  • Full connection (not supported by MySQL)

Left outer join

Only filter the right table, all the information in the left table is displayed

Syntax format: from table 1 left [outer] join table 2 on <connection condition>

The result is: all the records in Table 1 are included, and the records in Table 2 that do not meet the connection conditions are not included.

Right outer join

Only filter the left table, and display all the information in the right table

Syntax format: from table 1 right [outer] join table 2 on <connection condition>

The result is: all the records in Table 2 are included, and the records in Table 1 that do not meet the connection conditions are not included.

Seven, self-connection

A table is connected to itself, called the self-connection of the table

Note: You need to give the table an alias to distinguish; because all attribute names are attributes with the same name, you must use the alias prefix

E.g:
Query the student ID and name of the student whose birth date is the same as that of "Zhang Hong".
SELECT X.StudentID,X.studentName,X.Birth   FROM student AS X,student AS Y  where X.Birth=Y.Birth  and  Y.studentName='张宏‘

Eight, merge the result set

Use union to combine the query result sets of multiple select statements into one result set

Syntax: select field list 1 from table1 UNOIN [all] select field list 2 from table2

note:

  • The number of fields in field list 1 and field list 2 must be the same and have the same data type

  • The difference between union and union all: union will filter out duplicate records in the select result set, union all will directly merge the two result sets

Intersect and difference except are supported in SQL Server, but not in MySQL

Nested query

I. Overview

  • A select-from-where statement is called a query block

  • A query that nests a query block in the where clause or having phrase of another query block is called a nested query

Two, subquery

  • The relationship between the subquery and the parent query: the query result of the subquery is used as the query condition of the parent query

  • Restrictions on subqueries: order by cannot be used

  • Add parentheses for subqueries

  • Features: SQL statements allow multiple levels of nested queries; the level of nesting reflects the structure of SQL statements; part of the nested queries can be replaced by join operations

Three, irrelevant subqueries

  • Query subquery is not dependent on the parent query

  • Execution process: It is processed layer by layer from the inside to the outside. That is, the subquery is executed first (executed only once), and then the results of the subquery are used to establish the search conditions of its parent query

Four, related sub-queries

  • Query sub-query dependent on the parent query

  • The sub-queries whose inner conditions involve outer attributes are called correlated sub-queries

  • Implementation process:

    1. First, take the first tuple of the table in the outer query, and process the inner query according to its attribute values ​​related to the inner query. After executing the inner query, bring the query result into the outer query for query, you can get the result ;

    2. Then take the next tuple of the outer query;

    3. Repeat this process until all the outer surface is checked

Five, the predicate of the subquery

  • The result of the subquery can be a single attribute value or a collection

  • When the subquery returns only one value: use a comparison or IN/NOT IN

  • When only the query returns multiple values:

    1. IN or NOT IN: is or is not a value in the set

    2. (<>,>,<) ALL: not equal to, greater than or less than all the values ​​in the set

    3. (=,>,<)ANY: at least equal to, greater than or less than a value in the set

  • When a subquery returns a logical value: use exists/ not exists

6. Comparison of related subqueries and unrelated subqueries

Related subqueries:

  • The query condition of the subquery depends on the attribute value of the parent query and needs to be executed multiple times;

  • Processing method: from the outside to the inside! The parentheses can't be less!

Irrelevant subqueries:

  • The query condition of the subquery does not depend on the attribute value of the parent query, and only needs to be executed once;

  • Processing method: from the inside out! The parentheses can't be less!

note:

Replacement between different forms of queries:

  • All subqueries with in predicates, comparison operators, ANY and ALL predicates can be equivalently replaced with subqueries with exists predicates

  • Some subqueries with exists or not exists predicates cannot be equivalently replaced by other forms of subqueries

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_42248871/article/details/109910488