MySQL - add, delete, check and modify tables (1)

Table of contents

Table addition, deletion, query and modification (1)

One, create

1. Single row data + full column insert 

2. Multi-row data + specified column insertion

3. INSERT ELSE UPDATE

4. replace

二、Retrieve

1. select column

1. Full column query

2. Specify column query

3. The query field is an expression

4. Specify an alias for the query results

5. Deduplication of results

2. where conditions

1. Query students who failed in English and their English scores ( < 60 )

2. Query the students whose Chinese scores are in [80, 90] points and their Chinese scores

3. Query the students whose math scores are 65 or 85 or 98 or 99 and their math scores

4. Search for students surnamed Sun and a classmate named Sun

5. Inquire about students whose Chinese scores are better than English scores

6. Query the students whose total score is below 200

7. Query students whose Chinese score is > 80 and whose surname is not Sun

8. Inquire about a classmate Sun, otherwise the total score should be > 200 and the Chinese score should be < the math score and the English score should be > 80

9. Queries for NULL

3. Result sorting

1. Query classmates and math scores, and display them in ascending order of math scores

2. Query classmates and QQ numbers, and display them in ascending order of QQ numbers

3. Query students' scores in various subjects, and display them in descending order of mathematics, ascending order of English, and ascending order of Chinese

4. Query classmates and total scores, from high to low

5. Query the math scores of students surnamed Sun or students surnamed Cao, and the results are displayed in descending order of math scores

4. Filter paging results

1. Paging by id, with 3 records per page, showing pages 1, 2, and 3 respectively

三、Update

1. Change the math score of Sun Wukong to 80 points

2. Change Cao Mengde's mathematics score to 60 points and Chinese score to 70 points

3. Add 30 points to the mathematics scores of the top three students with the lowest total scores

4. Update the Chinese scores of all students to double the original

4. Delete

1. Delete data

1. Delete the test scores of Sun Wukong

2. Delete the entire table data

2. Truncate the table

5. Insert query results


Table addition, deletion, query and modification (1)

  • Table addition, deletion, query and modification are referred to as CRUD: Create (new), Retrieve (search), Update (modification), Delete (delete).
  • The operation object of CRUD is the data in the table, which is a typical DML (Data Manipulation Language) data manipulation language.

One, create

grammar:

 

INSERT [INTO] table_name [(column [, column] ...)]
VALUES (value_list) [, (value_list)] ...
value_list: value, [, value] ...

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

--创建一个学生表:
create table students(
    id int unsigned primary key auto_increment comment '主键',
    sn int not null unique comment '学号',
    name varchar(20) not null comment '姓名',
    qq varchar(20) comment 'qq号'
);

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

1. Single row data + full column insert 

Use the insert statement to insert records into the student table, insert a record into the table each time, and do not specify the column list (that is, id, sn, name, qq) when inserting the record, indicating that the entire column         is inserted according to the default column order in the table , so the column values ​​in each inserted record need to be listed sequentially in the order of the table columns. as follows:

2. 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:

Explanation:  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.

3. INSERT ELSE UPDATE

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 will be updated.

The syntax is as follows:

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

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 value of the specified update.
  • 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.

4. replace

-- 主键 或者 唯一键 没有冲突,则直接插入;
-- 主键 或者 唯一键 如果冲突,则删除后再插入
REPLACE INTO students (sn, name) VALUES (20001, '曹阿瞒');
Query OK, 2 rows affected (0.00 sec)
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,删除后重新插入

二、Retrieve

find data 

The syntax is as follows: 

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

case: 

-- 创建表结构
CREATE TABLE exam_result (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL COMMENT '同学姓名',
    chinese float DEFAULT 0.0 COMMENT '语文成绩',
    math float DEFAULT 0.0 COMMENT '数学成绩',
    english float DEFAULT 0.0 COMMENT '英语成绩'
);
-- 插入测试数据
INSERT INTO exam_result (name, chinese, math, english) VALUES
    ('唐三藏', 67, 98, 56),
    ('孙悟空', 87, 78, 77),
    ('猪悟能', 88, 98, 90),
    ('曹孟德', 82, 84, 67),
    ('刘玄德', 55, 85, 45),
    ('孙权', 70, 73, 78),
    ('宋公明', 75, 65, 30);

1. select column

1. Full column query

When querying data *, directly replace the column list with full-column query. At this time, all column information of the filtered records will be displayed. as follows: 

Usually it is not recommended to use * for full column query
  1. The more columns queried, the larger the amount of data that needs to be transferred;
  2. May affect the use of the index.

2. Specify 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: 

3. 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: 

Now that expressions can be executed, the following operations can be performed:

4. Specify an alias for the query results

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

5. Deduplication of results

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. If you want to deduplicate the query results, you can add distinct after select in SQL. as follows: 

2. where conditions

where child 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, then when querying data, the records that meet the conditions will be filtered out according to the where clause, 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:

operator illustrate
>、>=、<、<= greater than, greater than or equal to, less than, less than or equal to
=
equals, NULL is not safe, eg NULL = NULL results in NULL
<=>
equals, NULL safe, eg NULL <=> NULL evaluates to TRUE(1)
!=, <>
not equal to
BETWEEN a0 AND a1
Range matching, [a0, a1], if a0 <= value <= a1, return TRUE (1)
IN (option, ...)
Returns TRUE (1) if any of options
IS NULL
is NULL
IS NOT NULL
not NULL
LIKE
fuzzy match. % means any number (including 0) of any character; _ means any character

Logical Operators: 

operator illustrate
AND
If multiple conditions are TRUE (1) at the same time, the result is TRUE (1), otherwise FALSE (0)
OR
If either condition is TRUE (1), the result is TRUE (1), otherwise FALSE (0)
NOT
If the condition is TRUE(1), the result is FALSE(0); if the condition is FALSE(0), the result is TRUE(1)

Before starting to use the where clause below, you can look at this table first, and think about how to use where to quickly query the results for each of the following questions

 

1. Query students who failed in English and their English scores ( < 60 )

2. Query the students whose Chinese scores are in [80, 90] points and their Chinese scores

 We can also use between a0 and a1 ; it represents a closed interval

3. Query the students whose math scores are 65 or 85 or 98 or 99 and their math scores

 We can also use the in condition

4. Search for students surnamed Sun and a classmate named Sun

5. Inquire about students whose Chinese scores are better than English scores

6. Query the students whose total score is below 200

It should be noted that our Chinese+math+english alias is the total score. If you want to use this alias in where, it is not allowed:

Reason: What we want to query is the students whose total score is less than 200. Normal logic, if you have this table, you should first calculate the total score of all students, and then filter the students who are less than 200. The where clause is used for screening, and the total score needs to be calculated before screening, but if you use this alias directly, the where clause cannot be seen at all (do not know); remember: the where clause cannot use an alias;

7. Query students whose Chinese score is > 80 and whose surname is not Sun

8. Inquire about a classmate Sun, otherwise the total score should be > 200 and the Chinese score should be < the math score and the English score should be > 80

 

9. Queries for NULL

Here, the student table that demonstrated the newly added data is used to demonstrate the NULL query. The contents of the student table are as follows:

 Query students with qq numbers:

Query students who do not have a qq number:

Of course you can also do this:

<=>Operators can be used when comparing with NULL values , and =correct query results cannot be obtained by using operators. as follows: 

Because =operators are NULL-unsafe, using =an operator to compare any value to NULL returns NULL. as follows:

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

3. Result sorting

 The syntax is as follows:

SELECT ... FROM table_name [WHERE ...] ORDER BY column [ASC | DESC] [, ...];

1. Query classmates and math scores, and display them in ascending order of math scores

 If you want descending order, use desc:

2. Query classmates and QQ numbers, and display them in ascending order of QQ numbers

 Explain: NULL values ​​are considered smaller than any value, so they appear at the top when sorted in ascending order.

3. Query students' scores in various subjects, and display them in descending order of mathematics, ascending order of English, and ascending order of Chinese

 We found that math scores are indeed sorted in descending order, but English and Chinese scores are not;

  • The order by clause can specify sorting by multiple fields, and each field can specify sorting in ascending or descending order. Each field is separated by a comma, and the sorting priority is the same as the writing order.
  • For example, in the above SQL, when the math scores of the two records are the same, they will be sorted according to the English scores. If the English scores of the two records are also the same, they will continue to be sorted according to the Chinese scores, and so on.
     

4. Query classmates and total scores, from high to low

It should be noted that the alias specified in select can be used in the order by clause:

  • When querying data, the records that meet the conditions are first filtered out according to the where clause.
  • Then use the records that meet the conditions as the data source to execute the select statement in sequence.
  • Finally, sort the execution results of the select statement through the order by clause.

5. Query the math scores of students surnamed Sun or students surnamed Cao, and the results are displayed in descending order of math scores

 You can also not add the () in the where clause here, and it is more intuitive to add;

4. Filter paging results

Starting from the 0th record, filter out n records backward: 

SELECT ... FROM table_name [WHERE ..] [ORDER BY ...] LIMIT n;

Starting from the sth record, filter out n records backward:

SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT s, n;

Starting from the sth record, filter out n records backward:

SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n OFFSET s;

Suggestion: When querying unknown tables, it is best to add limit 1 after querying SQL to avoid database freezing due to excessive data in the table when querying full table data.

1. Paging by id, with 3 records per page, showing pages 1, 2, and 3 respectively

Here, the data in the score table is used to demonstrate the pagination query. The contents of the score table are as follows: 

When querying the records on page 1, after querying the SQL of the entire table data, add a limit clause to indicate that starting from the 0th record, filter out 3 records backward. as follows:

When querying the records on page 2, after querying the SQL of the data in the entire table, add a limit clause to indicate that starting from the third record, filter out 3 records backward. as follows:

When querying the records on page 3, after querying the SQL of the data in the entire table, add a limit clause to indicate that starting from the sixth record, filter out 3 records backward. as follows:

Explanation: If there are less than n records filtered out from the table, then only a few will be displayed .

三、Update

change the data 

UPDATE table_name SET column1=expr1 [, column2=expr2] ... [WHERE ...] [ORDER BY ...] [LIMIT ...];

1. Change the math score of Sun Wukong to 80 points

2. Change Cao Mengde's mathematics score to 60 points and Chinese score to 70 points

3. Add 30 points to the mathematics scores of the top three students with the lowest total scores

 Before modifying the data, first check the math scores of the three students with the bottom three total scores. as follows:

In the update statement, specify that the math scores of the filtered records should be added with 30 points, and check the data again after modification to ensure that the data has been successfully modified. as follows:

It should be noted that the compound assignment operator += is not supported in MySQL. In addition, when viewing the updated data, you cannot view the 3 students with the bottom three in the total score, because the 3 students with the bottom three in the total score were previously Classmates, after adding 30 points to the math score, it may no longer be the bottom three. as follows:

4. Update the Chinese scores of all students to double the original

Note: The statement that updates the entire table should be used with caution! 

4. Delete

delete data

The syntax is as follows: 

DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...];

1. Delete data

1. Delete the test scores of Sun Wukong

2. Delete the entire table data

Create a test table that contains a self-increasing primary key id and name, and insert some data. as follows: 

In the delete statement, only specify the name of the table whose data is to be deleted, without specifying the filter conditions through where, order by, and limit, and the data in the entire table will be deleted. as follows:

Then insert some data into the table, and do not specify the value of the auto-growth field when inserting the data. At this time, you will find that the auto-growth id value corresponding to the inserted data continues to grow on the previous basis. as follows:

When looking at the relevant information when creating a table, you can see that there is a field with AUTO_INCREMENT=N, which indicates that the value of the auto-increment field should be n when inserting data next time. as follows:

When deleting the entire table data through the delete statement, the AUTO_INCREMENT=N field will not be reset, so after deleting the entire table data, the auto-increment id value corresponding to the inserted data will continue to increase on the original basis. as follows:

Note: The operation of deleting the entire table should be used with caution!

2. Truncate the table

grammar:

TRUNCATE [TABLE] table_name;

Explain:

  • Truncate can only operate on the entire table, and cannot operate on partial data like delete.
  • Truncate does not actually operate on data, so it is faster than delete.
  • Truncate does not go through real transactions when deleting data, so it cannot be rolled back.
  • truncate will reset the AUTO_INCREMENT=n field.

Create a test table that contains a self-increasing primary key id and name, and insert some data. as follows:

In the truncate statement, only the name of the table whose data is to be deleted is specified, and the data of the entire table will be deleted at this time. However, since truncate does not actually operate on the data, after executing the truncate statement, it can be seen that the number of affected rows is 0. as follows:

Then insert some data into the table, and do not specify the value of the auto-growth field when inserting the data. At this time, you will find that the auto-growth id value corresponding to the inserted data is increased from 1 again. as follows:

When looking at the relevant information when creating a table, you can also see that there is a field with AUTO_INCREMENT=n, which indicates that the value of the self-increasing field should be n when inserting data next time. as follows:

However, when the entire table data is deleted through the truncate statement, the AUTO_INCREMENT field will be reset, so the auto-increment id value corresponding to the inserted data after the table is truncated will increase from 1 again. as follows:

Note: The truncation table operation should be used with caution!

5. Insert query results

The syntax is as follows: 

INSERT [INTO] table_name [(column1 [, column2] ...)] SELECT ... [WHERE ...] [ORDER BY ...] [LIMIT ...];

 Case: Delete duplicate records in the table, there can only be one copy of duplicate data

Create a test table that contains id and name, and insert some data (with duplicates) as follows: 

Now it is required to delete the duplicate data in the test table, the idea is as follows:

  • Create a temporary table with the same structure as the test table.
  • Query the data in the test table in a deduplicated manner, and insert the query results into the temporary table.
  • Rename the test table to another name, and then rename the temporary table to the name of the test table to achieve atomic deduplication.

Since the structure of the temporary table is the same as that of the test table, it can be created with like when creating the temporary table. as follows

Use the insert statement to insert the deduplicated query results into the temporary table. Since the structure of the temporary table and the test table are the same, and the select performs a full-column query, there is no need to specify the column list after the table name when inserting. as follows:

Rename the test table to another name (equivalent to backing up the data before deduplication, and delete it directly if not needed), rename the temporary table to the name of the test table, and then complete the deduplication of the data in the table operate. as follows:

 

Guess you like

Origin blog.csdn.net/sjsjnsjnn/article/details/128959848