[mysql]——Add, delete, modify and query tables

SQL

 

Table of contents

Preface 

(1) Create operation

1. Single row of data + full column insertion

2. Multiple rows of data + specified column insertion

3. Insert otherwise update

4. Direct replacement

(2) Retrieve operation

 1. SELECT column

1️⃣Full column query

2️⃣Specify column query

3️⃣The query field is an expression

4️⃣Specify aliases for query results

5️⃣Result deduplication

2, WHERE condition

3. Sorting of results

4. Filter paging results

(3) Update operation

(4) Delete operation

1. Delete data

2. Truncate table

(5) Insert query results

(6) Aggregation function

(7) Use of group by clause

Summarize


Preface 

CRUD refers to common operations on data storage systems, including Create, Retrieve, Update and Delete. It is a general data operation model widely used in databases and other data management systems.

Below is a brief description of each operation:

  1. Create : Used to create new records or entities into the data storage system. This can be inserting a new data record, creating a new file, or adding a new record to the database, etc.

  2. Retrieve : Used to read existing records or entities from the data storage system. This could be querying data in a database based on specific conditions, reading the contents of a file, or obtaining property values ​​of a specific object, etc.

  3. Update : used to modify existing records or entities in the data storage system. This could be updating information in a database, modifying the contents of a file, or changing an object's property value.

  4. Delete : Used to remove an existing record or entity from the data storage system. This can be deleting data from the database, deleting files, or destroying objects, etc.

These operations can be further extended and combined to meet more complex needs. Through the above operations, you can add, delete, modify and query the data in the table.


(1) Create operation

The CREATE operation in MySQL is used to create objects such as new databases, tables, views, indexes, or stored procedures. The following is a detailed explanation of several common uses of the CREATE operation in MySQL:

grammar:

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

value_list: value, [, value] ...

Case:

  • Next, I simply create a table named - students. details as follows:
 CREATE TABLE students (
    -> id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    -> sn INT NOT NULL UNIQUE COMMENT '学号',
    -> name VARCHAR(20) NOT NULL,
    -> qq VARCHAR(20) unique key
    -> );

  • The details are shown in the figure below:


1. Single row of data + full column insertion

 【illustrate】

  1. First of all, because there are no parentheses on the left side of values ​​to indicate the insertion situation, the default here is full insertion;
  2. Here, you don’t need to specify the id when inserting (of course, you need to explicitly insert data into those columns at that time), then mysql will use the default value for auto-increment;
  3. The order of columns and values ​​in the insert statement should match the order of columns defined in the table, and the corresponding values ​​should be provided in parentheses after the VALUES keyword. If some columns are allowed to be empty, NULL can be used to represent them.

2. Multiple rows of data + specified column insertion

Directly display the code. details as follows:

  •  Insert two records. The number of value_list must be consistent with the number and order of the specified columns.

3. Insert otherwise update

Insertion fails because the value corresponding to the primary key or unique key already exists:

In the above situation, we can selectively perform synchronization update operation syntax:
 

INSERT ... ON DUPLICATE KEY UPDATE
    column = value [, column = value] ...

Code sample: 

  • When we insert data, a row will often be displayed later: x row affected 


4. Direct replacement

Its function is very simple, as follows:

  1. -- If there is no conflict in the primary key or unique key, insert it directly;
  2. -- If the primary key or unique key conflicts, delete it and then insert it.
     

Code display:


(2) Retrieve operation

The Retrieve operation is used to retrieve data from the database. In MySQL, the commonly used Retrieve operation is to use the select statement to query.

grammar:

SELECT
    [DISTINCT] {* | {column [, column] ...}
    [FROM table_name]
    [WHERE ...]
    [ORDER BY column [ASC | DESC], ...]
    LIMIT ...

Case:

  •  Next, we perform the insert operation:


 1. SELECT column


1️⃣Full column query

To query the entire column of a table in MySQL, you can use the statement. This will return data for all columns and all rows in the table. SELECT *

  • Next, query the above table:

 【illustrate】

It is generally not recommended to use * for full column query:

  • 1. The more columns queried, the greater the amount of data that needs to be transmitted;
  • 2. May affect the use of the index. (The index will be explained later in the course)
     

2️⃣Specify column query
 

Therefore, based on the shortcomings of full-column queries, it is best to explicitly specify the required columns to reduce data transfer and query time.

  • If you only need a specific column in the query table, you can *replace with the name of the desired column, likeSELECT 列1, 列2, ... FROM 表名;
  • This improves query efficiency and reduces unnecessary data transfer.

3️⃣The query field is an expression

In MySQL, you can use expressions to query fields. Expressions can be mathematical operations, string operations, logical operations, or function calls, etc.

  • ①The expression does not contain fields

  • ②The expression contains a field

  •  ③The expression contains multiple fields

4️⃣Specify aliases for query results

In MySQL, you can use the as (writable or not) keyword to specify an alias for the query results.

grammar:

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

  • The following is an example (aliasing the above three subject scores):

  •  Or as follows:

5️⃣Result deduplication


2, WHERE condition

In MySQL, you WHEREcan use keywords to add conditions to filter query results. WHEREclause allows you to specify one or more conditions and only return rows that meet those conditions.

Comparison operators:
 

Logical Operators:
 

C language self-study notes——Operation symbols (6) - Zhihu

Case

  • ① Students who failed English and their English scores (< 60)


  • ②Students whose Chinese scores are [80, 90] and their Chinese scores

 Secondly, in addition to using and above, you can also use the [between and] expression:


  • ③ Students whose math scores are 58 or 59 or 98 or 99 and their math scores

In addition to the above methods, you can also use  IN conditions:


  • ④Classmates  named Sun and classmates named Sun
     

 Otherwise, _ matches exactly one arbitrary character:


  • ⑤ Students whose Chinese scores are better than their English scores


  • ⑥ Students whose total score is below 200 points


  • ⑦ Students whose Chinese score is >80 and whose surname is not Sun


  • ⑧ Student Sun, otherwise the total score is required to be > 200 and the Chinese score is < Mathematics score and the English score is > 80


  • ⑨ NULL query


3. Sorting of results

In MySQL, you can use ORDER BYthe clause to sort query results. ORDER BY clause allows you to specify one or more columns to sort by.

grammar:

-- ASC 为升序(从小到大)
-- DESC 为降序(从大到小)
-- 默认为 ASC

    SELECT ... FROM table_name [WHERE ...]
        ORDER BY column [ASC|DESC], [...];
  • Note : For queries without an ORDER BY clause, the order returned is undefined. Never rely on this order.
     

【Case】

  • ① Students and math scores are displayed in ascending order of math scores.


  • ② Classmates and QQ numbers, displayed in order by QQ numbers


  • ③ Check the scores of students in each subject, and display them in descending order of mathematics, ascending order of English, and ascending order of Chinese.


  • ④ Query classmates and total scores, from high to low

  •  In addition to the above methods, column aliases can also be used in the ORDER BY clause


  • ⑤ Query the math scores of students named Sun or Cao. The results are displayed in order of math scores from high to low.


4. Filter paging results

In MySQL, you can use LIMIT the and OFFSET keywords to filter paginated results.

  1. LIMIT Used to limit the number of rows returned in query results;
  2. It OFFSET is used to specify which row to start returning results from.

grammar:

-- Starting index is 0


-- Starting from s, filter n results

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


-- Starting from 0, filter n results

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


-- Starting from s, filter n results, which is more clear than the second usage. It is recommended to use

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

suggestion:

  • When querying an unknown table, it is best to add a LIMIT 1 to avoid the database being stuck due to querying the entire table data because the data in the table is too large.

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


(3) Update operation

In MySQL, you use UPDATE statements to modify data in database tables. UPDATEStatements are used to update one or more rows in a table.

grammar:

UPDATE table_name SET column = expr [, column = expr ...]
    [WHERE ...] [ORDER BY ...] [LIMIT ...]
  • Update column values ​​of query results
     

Case:

  • ① Change Sun Wukong’s math score to 80 points


  • ② Change Cao Mengde’s math score to 60 points and his Chinese score to 70 points


  • ③ Add 30 points to the math scores of the three students with the lowest total scores.


  • ④ Update the Chinese scores of all students to twice the original value

  • Note : Use the statement that updates the entire table with caution! ! !
     

(4) Delete operation

1. Delete data

grammar:

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


Case:

  • ① Delete Sun Wukong’s test scores
     

 


  • ② Delete the entire table data

 Next, we insert data:

 


2. Truncate table

In MySQL, you can use the statement to truncate (clear) data in a database table. This operation deletes all rows from the table and frees the associated storage space. TRUNCATE TABLE

grammar:

TRUNCATE [TABLE] table_name

Note: Use this operation with caution

  • 1. It can only operate on the entire table, and cannot operate on partial data like DELETE;
  • 2. In fact, MySQL does not operate on data, so it is faster than DELETE. However, when TRUNCATE deletes data, it does not go through the real transaction, so it cannot be rolled back.
  • 3. The AUTO_INCREMENT item will be reset
     

Prepare test data:

 

 

 


(5) Insert query results

In MySQL, you use statements to insert query results into a table. This makes it easy to insert query results from one table into another table as data. INSERT INTO ... SELECT

grammar:

INSERT INTO table_name [(column [, column ...])] SELECT ...

Case : Delete duplicate records in the table. There can only be one copy of duplicate data.

  • 1. Implement data preparation 

 Idea:

  • ① Create an empty table no_duplicate_table, the structure is the same as duplicate_table
     

 

  • ② Insert the deduplicated data of duplicate_table into no_duplicate_table

 

  • ③ Implement atomic deduplication operations by renaming the table

 


(6) Aggregation function

Aggregation functions are functions used to perform calculations and statistics on data, and they return a single result based on a set of values. In MySQL, common aggregate functions include the following:

How long does it take to learn SQL?  Do you have any good information or videos to recommend?  - Know almost

 

Case:

  • ① Count how many students there are in the class
     

 

  •  ② Count the number of QQ numbers collected by the class


 

 

  • ③ Count the number of math scores in this exam

 


  • ④ Total score of statistical mathematics scores

 


  • ⑤ Statistical average total score

 


  • ⑥ Return to the highest score in English

 


  • ⑦ Return > Minimum math score of 70 points or above
     

 


(7) Use of group by clause

The GROUP BY clause is a SQL statement used to group result sets. Through the GROUP BY clause, you can group query results according to specified columns and apply aggregate functions to each group for calculation.

The following are examples of usage of the GROUP BY clause:

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
  • In the above example, column1it is the name of the column that needs to be grouped, aggregate_function(column2)it is the aggregate function to be applied, and table_nameit is the name of the table.

For example, suppose we have a table called "orders" with columns "customer_id", "product_id" and "quantity", and we want to group orders by "product_id" and calculate the total sales of each product:

SELECT product_id, SUM(quantity)
FROM orders
GROUP BY product_id;
  • In the above example, the statement is used SELECT product_id, SUM(quantity) FROM orders GROUP BY product_idto group the "orders" table according to the "product_id" column, and apply the SUM aggregate function to the "quantity" column in each group to calculate the total sales volume of each product.

In addition to a single column, the GROUP BY clause can specify multiple columns for grouping, for example:

SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY column1, column2;

Summarize

The above is about common data query operations in mysql. Next, let’s briefly summarize the content of this article! ! !

Basic queries of MySQL data can be achieved by using the SELECT statement and other related clauses.

  • Query all columns:
SELECT * FROM table_name;

This will return all columns in the specified table.

  • Query specific columns:
SELECT column1, column2, ... FROM table_name;

You can specify the column names to query, separated by commas, to return data for only those columns.

  • Conditional query:
SELECT * FROM table_name WHERE condition;

Use the WHERE clause to add conditions and filter rows that meet the conditions. For example, WHERE age > 18rows with an age greater than 18 years old will be returned.

  • Use aggregate functions:
SELECT aggregate_function(column) FROM table_name;

Common aggregate functions include COUNT, SUM, AVG, MAX, and MIN. You can apply an aggregate function to a column and return the calculated result.

  • Sort query results:
SELECT * FROM table_name ORDER BY column ASC|DESC;

Use the ORDER BY clause to sort in ascending (ASC) or descending (DESC) order by specified columns.

  • Deduplication query results:
SELECT DISTINCT column FROM table_name;

Use the DISTINCT keyword to remove duplicate rows from query results and return only unique values.

  • Group query:
SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1;

Use the GROUP BY clause to group results and apply an aggregate function to each group.

At this point, the explanation of this data query ends. Thank you for watching and supporting! ! !

 

Guess you like

Origin blog.csdn.net/m0_56069910/article/details/132305315