MySQL - Section 6 - Addition, deletion, query and modification of MySQL tables

1. Overview of adding, deleting, checking and modifying MySQL tables

• CRUD for short: Create (add), Retrieve (find), Update (modify), Delete (delete).

• The operation object of CRUD is the data in the table, which is a typical DML (Data Manipulation Language) data manipulation language.


2.Create new data

2.1. insert command 

The insert command for adding new data is as follows:

INSERT [INTO] table_name [(column1 [, column2] ...)] VALUES (value_list1) [, (value_list2)] ...;

Explain:

• In SQL, capital letters represent keywords, and those in [ ] represent optional items.
• Each value_list in SQL represents a record to be inserted, and each value_list consists of several column values ​​to be inserted.
• The column list in SQL, which is used to specify which column in the table each column value in each value_list should be inserted into.

For demonstration, create a student table below, which contains self-increasing primary key id, student number, name and QQ number. as follows:

Check the table structure after creating the table, you can see the table structure is as follows:

2.2. Single row data + full column insert

Single row data + full column insert:

The following uses the insert statement to insert records into the student table. Each time a record is inserted into the table, and the column list is not specified when inserting the record, it means that all columns are inserted according to the default column order in the table. Therefore, in each inserted record Column values ​​need to be listed sequentially in the order of the table. as follows:

2.3. Multi-row data + specified column insertion

Multi-row data + specified column insertion:

Using the insert statement can also insert multiple records into the table at one time. The inserted multiple records are separated by commas, and when inserting records, only certain columns can be specified for insertion. as follows:

Note: When inserting records, only columns that are allowed to be empty or self-growth fields can be inserted without specifying a value, and columns that are not allowed to be empty must be inserted with a specified value, otherwise an error will be reported.

2.4. INSERT ELSE UPDATE

Insert otherwise updated usage scenario:

When inserting a record into a table, if the primary key or unique key in the record to be inserted already exists, the insertion will fail due to a primary key conflict or a unique key conflict. as follows:

At this time, you can optionally perform a synchronous update operation:

• If there is no conflicting data in the table, the data is inserted directly.

• If there is conflicting data in the table, the data in the table is updated.

The SQL for insert otherwise update is as follows:

INSERT ... ON DUPLICATE UPDATE column1=value1 [, column2=value2] ...;

Explain:

• In SQL, capital letters represent keywords, and those in [ ] represent optional items.
• The syntax after INSERT in SQL is the same as the previous INSERT statement.
• The column=value after UPDATE indicates the column value that needs to be updated when there is a conflict in the inserted record.

insert else update:

For example, when inserting a record into the student table, if there is no primary key conflict, the record will be inserted directly. If there is a primary key conflict, the student number and name of the conflicting record in the table will be updated. as follows:

After executing the SQL for inserting or updating, you can judge the insertion status of this data by the number of affected data rows:

• 0 rows affected: There is conflicting data in the table, but the value of the conflicting data is the same as the specified update value (the data to be updated is the same as the original data).
• 1 row affected: There is no conflicting data in the table, and the data is inserted directly.
• 2 rows affected: There is conflicting data in the table, and the data has been updated.

2.5. Replace data

Replacement data:

• If there is no conflicting data in the table, the data is inserted directly.

• If there is conflicting data in the table, delete the conflicting data in the table first, and then insert the data.

To achieve the above effect, you only need to change the INSERT in the SQL statement to REPLACE when inserting data. for example:

After executing the SQL for data replacement, you can also judge the insertion status of this data by the number of affected data rows:

• 1 row affected: There is no conflicting data in the table, and the data is inserted directly.

• 2 rows affected: There is conflicting data in the table, and the conflicting data is deleted and reinserted.


3.Retrieve  find data

3.1. select command

The SQL to find the data is as follows:

SELECT [DISTINCT] {* | {column1 [, column2] ...}} FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...];

Explain:

• In SQL, capital letters represent keywords, and those in [ ] represent optional items.

• The | in { } means that the statement on the left or the statement on the right can be selected.

For demonstration, create a score table below, which contains the self-increasing primary key id, name, and the student's Chinese score, math score, and English score. as follows:

Check the table structure after creating the table, you can see the table structure is as follows:

Next, insert a few test records into the table for us to find. as follows:

3.2. SELECT columns

Full column query:

When querying data, directly use * to replace the column list, which means to perform a full-column query, and then all column information of the filtered records will be displayed. as follows:

Note: In general, it is not recommended to use * for full-column query, because the queried data needs to be transmitted from the MySQL server to the host through the network. The more columns queried, the larger the amount of data to be transmitted. In addition, Performing full-column queries may also affect the use of indexes.

Specified column query:

When querying data, you can also only query the specified columns. At this time, you can list the columns that need to be queried in the column list. as follows:

The query field is an expression:

When querying data, in addition to the column names that can be listed in the column list, we can also list expressions in the column list. as follows:

Because select can be used not only to query data, but also to calculate certain expressions or execute certain functions. as follows:

If we list the expression in the column list, the expression will be executed every time a record is filtered out, and then the calculation result of the expression will be displayed as a column value of the record.

The expression in the column list can contain the existing fields in the table. At this time, whenever a record is filtered out, the corresponding column value in the record will be provided to the expression for calculation. as follows:

The expressions in the column list can also contain existing fields in multiple tables, then we can calculate more meaningful data through the expressions. as follows:

Specify an alias for query results:

The SQL to specify an alias for a query result is as follows:

SELECT column [AS] alias_name [...] FROM table_name;

Explain:

• In SQL, capital letters represent keywords, and those in [ ] represent optional items.

For example, when querying the data in the grade table, add the three subjects in each record, and then assign the alias name of the column corresponding to the calculation result to "total score". as follows:

Result deduplication:

When querying the score table, specify the column corresponding to the query math score, and you can see that there are repeated scores in the math score. as follows:

If you want to deduplicate the query results, you can add distinct after select in SQL. as follows:

3.3.WHERE condition

WHERE condition:

The difference of adding a where clause:

• If the where clause is not specified when querying data, all the records in the table will be directly used as the data source to execute the select statement in sequence.
• If the where clause is specified when querying data, the records that meet the conditions will be filtered out according to the where clause when querying data, and then the select statement will be executed sequentially using the records that meet the conditions as the data source.
One or more filter conditions can be specified in the where clause, and logical operators AND or OR are used to associate each filter condition. The comparison operators and logical operators commonly used in the where clause are given below.

Comparison operators:

Logical Operators:

Query the students who failed in English and their English scores:

In the where clause, indicate that the filter condition is that the English score is less than 60, and in the column list of select, specify that the columns to be queried are name and English score. as follows:

Query the students whose Chinese scores are between 80 and 90 and their Chinese scores:

In the where clause, indicate that the filter condition is that the Chinese score is greater than or equal to 80 and less than or equal to 90, and in the column list of select, specify that the columns to be queried are name and Chinese score. as follows:

In addition, BETWEEN a0 AND a1 can also be used here to indicate the range of the language score. as follows:

Query students whose math scores are 58 or 59 or 98 or 99 and their math scores:

In the where clause, indicate that the filter condition is that the math score is equal to 58 or 59 or 98 or 99, and in the column list of select, specify that the column to be queried is name and math score. as follows:

In addition, the method of IN(58,59,98,99) can also be used here to judge whether the math scores meet the screening requirements. as follows:

Query the classmate surnamed Zhao and Zhao classmate respectively:

Query students with the surname Zhao:

In the where clause, use fuzzy matching to judge whether the current classmate’s surname is Zhao (you need to use % to match multiple characters), and specify the column to be queried as name in the column list of select. as follows:

Inquire about a classmate named Zhao:

In the where clause, judge whether the current classmate is Zhao through fuzzy matching (you need to use _ to strictly match a single character), and specify the column to be queried as name in the column list of select. as follows:

Query students whose Chinese scores are better than English scores:

In the where clause, indicate that the filter condition is that the Chinese score is greater than the English score, and in the column list of select, specify that the columns to be queried are name, Chinese score, and English score. as follows:

Query students whose total score is below 200 points:

Add an expression query to the column list of select. The expression of the query is the sum of Chinese, mathematics and English scores. For the convenience of observation, you can specify an alias for the column corresponding to the expression as "total score", and specify the filter in the where clause The condition is that the sum of the three subjects is less than 200. as follows:

It should be noted that the alias specified in select cannot be used in the where clause:

• When querying data, first filter out qualified records according to the where clause.
• Then use the records that meet the conditions as the data source to execute the select statement in sequence.
That is to say, the where clause is executed before the select statement, so an alias cannot be used in the where clause. If an alias is used in the where clause, an error will be reported when querying data. as follows:

Query for students whose Chinese score is greater than 80 and whose surname is not Zhao:

In the where clause, indicate that the filter condition is that the Chinese score is greater than 80, and use fuzzy matching and not to ensure that the student's surname is not Zhao, and specify the column to be queried as name and Chinese score in the column list of select. as follows:

Query Zhao, otherwise, the total score is greater than 200 and the Chinese score is lower than the math score and the English score is greater than 80 points:

The requirement of this topic is to check the results. The person to be queried is either Zhao, or the total score is greater than 200 points and the Chinese score is less than the math score and the English score is greater than 80 points. Fuzzy matching, expression query and logical operations are required for query. symbol. as follows:

NULL query:

Prepare the test form:

Query students with known QQ numbers:

In the where clause, indicate that the filter condition is that the QQ number is not NULL, and in the column list of select, indicate that the columns to be queried are name and QQ number. as follows:

 

Query students with unknown QQ numbers:

In the where clause, indicate that the filter condition is QQ number is NULL, and in the column list of select, specify the columns to be queried as name and QQ number. as follows:

It should be noted that the <=> operator should be used when comparing with NULL values, and the = operator cannot get correct query results. as follows:

Because the = operator is NULL-unsafe, using =the operator to compare any value to NULL returns NULL. as follows:

But the <=> operator is NULL-safe. Using the <=> operator to compare NULL with NULL returns TRUE (1), and comparing a non-NULL value with NULL returns FALSE (0). as follows:

3.4. Result sorting

3.5. Filter paging results


4.Update modify data


5.Delete delete data


6. Insert query results


7. Aggregate functions


8. Group query

Guess you like

Origin blog.csdn.net/qq_45113223/article/details/131331129