4. Single table query

Grammatical format hints in SQL sentences:

1. The content in square brackets ([]) is optional;

2. [, ...] means that the previous content can be repeated;

3. Curly brackets ({}) and vertical bars (|) indicate options, and only one of the options needs to be selected;

(1) Concept

Query refers to obtaining the required data from the database, and different data can be obtained by using different query methods. Generally, a query involving only one data table is called a single-table query.

(2) SELECT statement

The basic statement to query data from the data table is the SELECT statement, and the basic syntax of the SELECT statement is as follows:

(3) Simple query

3.1: Query all fields:

Querying all fields refers to returning the values ​​of all fields that meet the conditions in the data table. There are two ways to query all fields, namely to list all field names to query and to use wildcard * to query.

(1) List all field names for query:

SELECT field name 1, field name 2,... FROM data table name;

(2) Use the wildcard * to query:

SELECT * FROM data table name;

3.2: Query specified fields:

SELECT field 1, field 2,... FROM data table name;

The fields 1...n above indicate the field names to be queried.

3.3: Query deduplicated data:

If the field of the data table does not have a unique constraint, then the field may store duplicate values. Sometimes it is necessary to remove the duplicate values ​​in the result and display them. MySQL provides the DISTINCT keyword to remove duplicate values ​​when querying. , the syntax is as follows:

SELECT DISTINCT field name FROM data table name;

extension:

The DISTINCT keyword can act on multiple fields, the syntax is as follows:

SELECT DISTINCT field name 1, field name 2,... FROM table name;

(4) Condition query

4.1: Queries with comparison operators:

MySQL provides a series of comparison operators, which can be used to filter data when querying data. The comparison operators commonly used in MySQL are shown in the table below.

4.2: Queries with logical operators:

 

(5) Advanced query

5.1: Aggregation query:

5.2: Group query:

5.3: Sort queries:

 5.4: Limited query:

5.5: Built-in functions:

(6) Set an alias

When querying data, you can take an alias for the data table and word end, and you can use this alias to replace the original data table name and field name.

6.1: Set an alias for the data table:

 6.2: Set an alias for the field:

 

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/131196059