[MySQL] Basic operations of tables

Basic table operations

According to what we learned in the previous section, our database should now have tables created. Since in a relational database, tables are used to store data, the basic operation of the table is actually adding, deleting, checking, and modifying data, referred to as CRUD (create,retrieve,update,delete)If arranged in English, the actual order should be addition, search, modification and deletion

Then let’s look at how to perform these operations separately.

Add data

Insert specified column

Although we said that the English word to add is create, the actual keyword used is not create. Let’s look at the syntax for adding data< /span>

INSERT INTO 表名 (列名1,列名2....) VALUES (对应数据1), (对应数据2).....;

After reading this long paragraph, you may still be a little confused, thinking: What is this thing listed as 123, and what is the corresponding data? In order to understand what is being said here, let’s look directly at an example


First we create a student table, which contains two attributes: student code and student name

CREATE TABLE IF NOT EXISTS student(id INT, name VARCHAR(20));

At this time I want to add some data to it: No. 1 Zhang San, No. 2 Li Si, No. 3 Wang Wu

Then according to the instructions above, we can write like this

INSERT INTO student (id, name) VALUES (1, '张三'), (2, '李四'), (3, '王五');

Note: The string in MySQL can be enclosed in double quotes or single quotes, both representing strings

Now let's combine this example to see what our grammar means. In fact, column names 1 and 2 are the columns where you want to fill in the data. The following corresponding data 1 and corresponding data 2 correspond to the data entered in the column you specified earlier.

For example, if I want to add a student now, he only has a code number of 4, but no name, so he should write it like this (at this time, the position where no data is given will be automatically left blank)

INSERT INTO student (id) VALUES (4);

So now someone may have a question: When I added three pieces of data above, can I add them one by one? The answer is: of course. But this will be less efficient than inserting three pieces of data at once. Why is this?

Let’s recall what we said in the previous section that MySQL is a software with 客户端-服务器 structure. Every time the client we operate performs an operation, it must send a request to the server, and then the server will Return a response, then if we make three requests respectively, the server will also return three responses. But if we directly insert 3 data at one time, then we only need to request once, and the server only needs to respond once, so the efficiency will be significantly improved. Still taking the restaurant as an example, if I am a customer and I want to order three dishes, then if I only say one dish at a time, and then wait for the restaurant to finish cooking one dish, I will tell it what I want for the next dish. I definitely have never said to a restaurant at once: "I want these three dishes." They came quickly


Full column insert

In addition, we can also not write which columns we want to enter data into when inserting data, but this means that by default you have to insert data into all columns, and if the data type and column you give do not match at this time, an error will be reported directly. (The order of the columns corresponds to the order you gave when you created it)

For example, let’s modify the above statement to insert the data of 3 people.

INSERT INTO student VALUES (1, '张三'), (2, '李四'), (3, '王五');

But if I change the order at this time, an error will be reported

INSERT INTO student VALUES ('张三', 1);

Insert image description here

Including if I want to insert a data with only id it will not work

Insert image description here

Find data

Specify column query

Above we learned how to insert data. Next, if we want to see the data we inserted, we can use the data search statement. The syntax is as follows

SELECT 列名1, 列名2.... FROM 表名;

For example, if I want to see the student code and student name I just inserted, I can enter the following statement (no brackets are needed in the column name at this time)

SELECT id, name FROM student;

Full column query

Similarly, we can also perform a full column query here, but it does not mean writing nothing, but writing a * number

SELECT * FROM 表名;

But note that this is a dangerous operation when actually using the database. Why? Because in actual application scenarios, the amount of data stored in the database is very large. Querying all the data at one time may cause the database server to freeze, causing the database server to be inaccessible, thus causing immeasurable losses. . Therefore, when we query data, we generally do not query the entire column, or we add some conditions and then search to filter the data. As long as we find the data we want, don't search all of them.

Conditional query

Conditional query, as the name suggests, can filter out some data through certain conditions, so that the required data can be obtained more quickly.

SELECT 列... FROM 表名 WHERE 条件表达式;

To perform conditional query, first we need to borrow the WHERE keyword, and then write the filtering conditions through conditional expressions. So how to write a conditional expression?

Let’s first look at some operators used to write conditional expressions

conditional operator

operator significance
>, <, >=, <= Greater than, less than, greater than or equal to, less than or equal to
= Equals (cannot perform NULL operation)
<=> Equal to (can perform NULL operation)
!=, <> Not equal to (cannot perform NULL operation)
IS NULL is NULL
IS NOT NULL Not NULL
BETWEEN…AND… Range matching, both sides are closed intervals, if the data is within the range, it is TRUE(1)
IN(…) If the data is any data in the brackets, the result is TRUE(1)
LIKE Fuzzy matching, see the case for details

Logical Operators

operator significance
AND and
OR or
! No

The operators here also have priorities, but we don’t have any need to remember them. If we don’t want query results that don’t meet the requirements due to operator priorities, we can add some more parentheses.


Next, let’s use some examples to demonstrate the effects of all the operators listed above.

First create a score table and insert some data

CREATE TABLE exam_result(id INT, name VARCHAR(20),
                         chinese DECIMAL(3, 1), 
                         math DECIMAL(3, 1), 
                         english DECIMAL(3, 1));
INSERT INTO exam_result VALUES (1, '张三', 98.0, 85.5, 87.5),
                               (2, '李四', 87.0, 60.5, 75.5),
                               (3, '王五', 64.5, 70.0, 90.0),
                               (4, '赵六', 77.0, 95.5, 69.0),
                               (5, '田七', 88.0, 74.5, 86.0),
                               (6, '孙行者', 50.0, 60.0, 70.0),
                               (7, '行孙者', 83.0, 75.0, 60.0),
                               (8, '者行孙', 99.0, 93.5, 83.0),
                               (9, '孙权', 87.5, 83.5, 88.0);

First, let’s look at the first few< > <= >=, it’s very simple and go directly to the case

#查询语文大于85分的人的所有信息 
SELECT * FROM exam_result WHERE chinese > 85;

The other operators are the same and will not be shown again. Let’s look at = next. It is also very simple and straightforward to use the case

#查询数学成绩为75分的人的所有信息
SELECT * FROM exam_result WHERE math = 75;

But note that if this= encounters NULL during the comparison, the result will be directly NULL, also is FALSE

For example, let's insert another data with NULL in the score here.

INSERT INTO exam_result VALUES (10, '唐三藏', NULL, NULL, NULL);

At this time, if we try to use = to find the data with NULL, we will find that nothing is found

SELECT * FROM exam_result WHERE chinese = NULL;

Insert image description here

So if you want to filter the data with NULL, you need to use <=> or IS NULL

SELECT * FROM exam_result WHERE chinese <=> NULL;
#或者用下面的写法
SELECT * FROM exam_result WHERE chinese IS NULL;

This part!= <> is the same, and it cannot be compared with NULL. If you want to compare it with NULL, then You should use IS NOT NULL, or use the logical operators ! and <=> together. Two correct comparison cases are as follows

SELECT * FROM exam_result WHERE chinese IS NOT NULL;
#或者可以用下面的写法 当前还没有讲解!的使用 看一下即可
SELECT * FROM exam_result WHERE !(chinese <=> NULL);

Next, let’s look at three more special conditional operators. The first isBETWEEN...AND.... Let’s look at a case first

#搜索数学成绩在60到70的人
SELECT * FROM exam_result WHERE math BETWEEN 60 AND 70;

Insert image description here

At this time we can find that people with math scores equal to 60 and equal to 70 have also been queried, because BETWEEN...AND...Both sides of the boundaries are closed intervals (that is, boundary values ​​will be included)


INAlthough it seems a bit abstract, we can immediately understand it as soon as we look at the example. Let’s go directly to the example.

#搜索数学成绩等于60, 70, 80, 90的人
SELECT * FROM exam_result WHERE math IN (60, 70, 80, 90);

This actually only filters out the data that is equal to the situation we listed, which is equivalent to condensing multiple equal signs together.


LIKEIt is generally used to perform string queries. For example, I can use it to: query the results of a person named Li, and query the results of a person whose name contains Sun.

When using LIKE to query, we use two special symbols and string combinations to achieve a fuzzy matching effect: % is used Replace any number of characters, including zero characters. _ can only be used to replace one character

Let’s look directly at the example and combine each query statement with the above comments to understand the fuzzy matching rules.

#查询名字里面带孙字的人
SELECT * FROM exam_result WHERE name LIKE '%孙%';

#查询名字为两个字且姓王的人
SELECT * FROM exam_result WHERE name LIKE '王_';

#查询名字第二个字为孙字的人
SELECT * FROM exam_result WHERE name LIKE '_孙%';

#查询名字里面最后一个字为孙字的人
SELECT * FROM exam_result WHERE name LIKE '%孙';

#查询姓孙的人
SELECT * FROM exam_result WHERE name LIKE '孙%';

Logical operators are actually very easy to understand. Logical operators operate on existing conditional expressions. Just look at a few examples.

#搜索数学大于80分,并且英语小于90分的人
SELECT * FROM exam_result WHERE math > 80 AND english < 90;

#搜索语文小于80分,或者英语大于80分的人
SELECT * FROM exam_result WHERE chinese < 80 OR english > 80;

Or I want to reverse the conditions: search for people with a math score of 90 or above. At this time, I can write directlymath > 90, but I can also use !Logical inversion to achieve the same result

#搜索数学在90分以上的人
SELECT * FROM exam_result WHERE !(math <= 90);

refers to the fact that when AND and OR are used at the same time, some operator priority problems may occur, so in multiple It is recommended to add parentheses when using both at the same time

Paging query

Sometimes, even if we use conditional queries, the data displayed at one time is still too much. At this time, we hope to further reduce the amount of data displayed through other methods. Then we can use paging queries to do this. The syntax is as follows

SELECT * FROM exam_result LIMIT 单次查询的数据量 OFFSET 偏移量

The amount of data in a single query is easy to understand. It is the amount of data we want to query at one time. The offset refers to the position from which the query should be started (the offset of the first position is 0, similar to the bottom of the array). standard)

Here we still use the data from the score table in the previous part to give an example. Let’s look at the example directly.

#查询前三条数据
SELECT * FROM exam_result LIMIT 3 OFFSET 0;

If we want to start querying from the 4th piece of data, then we will changeOFFSET to 3, and so on for the others

#从第四条数据开始查询
SELECT * FROM exam_result LIMIT 3 OFFSET 3;

There are also some writing methods. Let’s take a brief look at them. When we use paging queries, we mainly use the above method.

#查询x条数据,默认OFFSET为0
SELECT * FROM exam_result LIMIT x;

#查询x条数据,OFFSET为y
SELECT * FROM exam_result LIMIT y, x;

Expression query

Expression query allows us to directly perform operations on columns when querying. For example, if we want to query the sum of students' grades, we do not need to create a new table and create a new column to calculate by ourselves. We can directly use expressions. Query, the syntax is as follows

SELECT 列名/表达式 FROM exam_result;

Here is an example of finding the total scores of students

#查询语文+数学+英语的总和
SELECT id, name, chinese + math + english FROM exam_result;

Including we can also query similar expressions such as minus 10 points for Chinese, plus 10 points for English, etc.

#查询数学+10分后的结果
SELECT id, name, math + 10 FROM exam_result;

At this time, someone may have some questions: Will my expression operation affect the data stored in our database?

The answer is no. First of all, what we perform is not a modification operation, but a query operation. And the table we see at this time is not actually an actual table in the database, but a temporary table returned to us by the server. Therefore, even if we modify the data on this temporary table, the data stored in the database will not change. will not change

Alias ​​query

After using expression query, we will find that sometimes some expressions are too cumbersome and a long list is very ugly and unintuitive. Then we can use alias query to give our expression an alias. The syntax is as follows

SELECT 列名/表达式名 AS 别名 FROM 表名;

For example, we will give the chinese + math + english of the total score query above an alias of total

#查询语文+数学+英语的总和,并且将表达式命名为total
SELECT id, name, chinese + math + english AS total FROM exam_result;

And we can also perform alias queries on column names, or take multiple aliases at the same time

#分别赋予别名
SELECT id AS student_id, name AS student_name, chinese + math + english AS total FROM exam_result;

sort query

We can also sort the queried data, the syntax is as follows

SELECT 列名 FROM 表名 ORDER BY 列名 排序方式;

There are two sorting methods: asc and desc, which refer to ascending order and descending order respectively (you can also not specify the sorting method, in which case the default in ascending order)

For example, I want to query data sorted by math scores in descending order

#根据数学成绩降序排序
SELECT id, name, math FROM exam_result ORDER BY math DESC;

In addition, we can also use aliases to sort, but the premise is that this alias must be set before

For example, set an alias for the expression that calculates the total scoretotal, and use total to sort the queried data

#根据总成绩降序排序
SELECT id, name, chinese + math + english AS total FROM exam_result ORDER BY total DESC;

We can also use the columns we did not query to sort

For example, we query Chinese scores, but they are sorted by English scores.

#根据英语成绩升序排序,但是没有查询英语列
SELECT id, name, chinese FROM exam_result ORDER BY english ASC;

Deduplication query

Deduplication query, as the name suggests, can help us deduplicate data with the same content and only display it once. The syntax is as follows

SELECT DISTINCT 列名 FROM 表名;

In order to test the effect, we first add two data with the same math scores to this score table.

INSERT INTO exam_result (id, name, math) VALUES (11, '孙悟空', 90.0), (12, '沙悟净', 90.0);

Then we directly query a wave of math scores without deduplication, and in order to be able to observe intuitively, we use a sorting

SELECT math FROM exam_result ORDER BY math;

At this time we will find that the data with math score90.0 appears twice
Insert image description here

Next, we add the deduplication keyword and query again

SELECT DISTINCT math FROM exam_result ORDER BY math;

Then at this time we will find that the data with the math score 90.0 will only appear once

Insert image description here

But note that if we query another data like id or name at this time, then the two mathematics scores at this time will be The data of 90.0 will no longer be considered as duplicates and will not be deduplicated

Summarize

The many different query modes mentioned above were not mixed in order to facilitate understanding, but in fact they can also be mixed and used. It does not mean that I can only use one query method at a time. For example, I can sort and perform paging. Query and similar operations. But I leave this to you to research on your own.

delete data

The syntax for deleting data is generally borrowed from the conditional syntax of conditional query. The syntax is as follows

DELETE FROM exam_result WHERE 条件表达式;

Just look at the example

#删除全部成绩都为空的数据
DELETE FROM exam_result WHERE chinese IS NULL AND math IS NULL AND english IS NULL

There is not much to say about deletion. The main core is the writing of conditional syntax.


In fact, we can also not use any conditional syntax, but this is a dangerous operation. It directly deletes the data of the entire table. It is not recommended. You must confirm that you want to perform such an operation before using it.

change the data

Modifying data generally requires borrowing the conditional syntax of conditional query, otherwise the consequences are the same as above. The syntax for modifying data is as follows

UPDATE 表名 SET 要修改的列 = 要设定的数据 WHERE 条件表达式;

Let’s look directly at an example

#将11号同学的英语成绩修改为85.5分
UPDATE exam_result SET english = 85.5 WHERE id = 11;

We can also directly modify the column to be modified based on itself.

#将11号同学的英语成绩加10分
UPDATE exam_result SET english = english + 10 WHERE id = 11;

But at this time, if we try to multiply the columns in it by two, an error may be reported.

#给11号同学的英语成绩乘2
UPDATE exam_result SET english = english * 2 WHERE id = 11;

Insert image description here

Because our result data exceeds the expression range ofDECIMAL(3, 1) at this time, be careful not to exceed the expression range of the data type when performing modification operations


If no conditions are specified, the data of all rows in this column will be directly modified here. Be sure to confirm repeatedly when performing such an operation to avoid irreparable consequences due to misoperation.

Guess you like

Origin blog.csdn.net/qq_42150700/article/details/132883804