MySQL database, detailed explanation of adding, deleting, modifying and checking tables

Table of contents

1.CRUD

2. Increase data

2.1 Create data

2.2 Insert data

2.2.1 Single row insertion

2.2.2 Multi-line insertion

3. Find data

3.1 Full column query

3.2 Specified column query

3.3 The query field is an expression

3.3.1 Expression does not contain fields

3.3.2 An expression contains a field

3.3.3 Expression contains multiple fields 

Aliases from 3.4

3.5distinct (deduplication)

3.6 order by (sorting)

3.6.1 A field is sorted by default

3.6.2 Sort a field in descending order

3.6.3 Sorting using expressions and aliases

3.6.4 Sorting multiple fields

3.7where (condition query)

3.7.1 Comparison Operators

3.7.2 Logical operators

3.8limit (pagination)

4. Modify data

5. Delete data

1.CRUD

CRUD is the first letter of several sql statements that are added, deleted, modified, and checked, namely create (create), query (retrieve), update (update), and delete (delete).


2. Increase data


2.1 Create data

To create a database, the syntax is: create database database name; for example, to create a database named test:

mysql> create database test;
Query OK, 1 row affected (0.00 sec)

When the Query Ok field appears in the last line, it means that the database is created successfully. 


To create a table, the syntax is: create table table name; for example, to create a table named student:

mysql> use test;
Database changed
mysql> create table student(
    -> id int,
    -> name varchar(20),
    -> price decimal
    -> );
Query OK, 0 rows affected (0.02 sec)

When we create a table, we must first use a database. After the table is successfully created, the last line of statement will prompt the Query Ok.. statement.


2.2 Insert data


2.2.1 Single row insertion

When we create a table, there is no information in the table so we have to insert some data to store. We use insert into table name values(field 1, field 2,....); to insert some data, note that the inserted data should have the same structure as the table. We insert a row of information into the student table:

mysql> insert into student values(1,'张三',20);
ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1

We can see that there is an ERROR (error). It means that the string Zhang San has not introduced the utf-8 format, so when we create the database, we must first declare the utf8 format so that the addition of data will not cause errors, as shown below:

mysql> create database test charset utf8;
Query OK, 1 row affected (0.00 sec)

In this way, when we create the database, we also declare that the character set is utf-8 type, so that we will not make mistakes when creating tables and adding new data. Declare character set syntax: charset character set type .

mysql> use test;
Database changed
mysql> create table student(
    -> id int,
    -> name varchar(20),
    -> price decimal
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> insert into student values(1,'张三',20);
Query OK, 1 row affected (0.00 sec)

We can see that the last row of data is inserted, prompting Query OK, this is a single-row insert operation, let's look at multi-row insert.


2.2.2 Multi-line insertion

The multi-line insert syntax is: insert into table name (type 1, type 2, type 3,...) values ​​(field 1, field 2, field 3,...), (field 1, field 2, field 3, ...);

mysql> insert into student(id,name,price) values
    -> (2,'李四',24),
    -> (3,'王五',30);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

The above code adds two more rows of data to student, so there are now three rows of data in the student table. We can use select * from student; full column query to view the student table structure.

mysql> select * from student;
+------+------+-------+
| id   | name | price |
+------+------+-------+
|    1 | 张三 |    20 |
|    2 | 李四 |    24 |
|    3 | 王五 |    30 |
+------+------+-------+
3 rows in set (0.00 sec)

Of course, I added the three fields of id, name, and price to the above multi-line insertion. You can also add any number of these three fields arbitrarily, such as adding only the two fields of id and name, and so on. 


3. Find data


3.1 Full column query

Full-column query, that is, to query the data in the entire table. The syntax format is: select * from table name; where * is a wildcard representing all data. For example, to query all the data in the student table above:

mysql> use test;
Database changed
mysql> select * from student;
+------+------+-------+
| id   | name | price |
+------+------+-------+
|    1 | 张三 |    20 |
|    2 | 李四 |    24 |
|    3 | 王五 |    30 |
+------+------+-------+
3 rows in set (0.00 sec)

We can see that all the data is displayed, which is the full column query. But note, in our actual development process, the * symbol must not be used arbitrarily. When we use * to query a huge data table or other types of data, all the memory is occupied, and the database will not update or add data normally, which is very dangerous! Therefore, we can try it on our own computer, because our database is small and there is a high probability that there will be no risk of data loss.


3.2 Specified column query

In the above we know that the * number is very dangerous, so it is safer to query the specified column. We can directly query the data of a certain column, so that the memory usage is very low. The specified column query syntax is: select field 1, field 2 from table name; if I want to find the two columns of data in the student table, id and name:

mysql> select id,name from student;
+------+------+
| id   | name |
+------+------+
|    1 | 张三 |
|    2 | 李四 |
|    3 | 王五 |
+------+------+
3 rows in set (0.00 sec)

We can see that the query of the specified column is very "humanized". We can query the data in the column we want to query, so that the memory usage will be very low. This query method is recommended.


3.3 The query field is an expression

First, we create a grade table and insert two rows of data:

mysql> create table grades(
    -> chinese int,
    -> math int,
    -> english int);
Query OK, 0 rows affected (0.03 sec)
mysql> insert into grades(chinese,math,english) values
    -> (78,98,59),
    -> (76,99,35);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

The above creates a score table very well, and this table has two rows of data. Then creating tables and inserting table information has been explained above, and unskilled partners can go and have a look.


3.3.1 Expression does not contain fields

When the expression does not contain fields, it means that any information in this expression is not any field in the table. For example, query a field named 10 in the following subscript:

mysql> select chinese,math,english,10 from grades;
+---------+------+---------+----+
| chinese | math | english | 10 |
+---------+------+---------+----+
|      78 |   98 |      59 | 10 |
|      76 |   99 |      35 | 10 |
+---------+------+---------+----+
2 rows in set (0.00 sec)

We can see that the number of columns in this expression is 10. Such a query is a query whose expression does not contain fields. Note that the fields here are the column names of each column in the table.


3.3.2 An expression contains a field

When the expression contains a field, we usually use this operation when we want to change the data of a certain column in the table. For example, I want to increase the English score of everyone in the grades table by 10 points:

mysql> select chinese,math,english+10 from grades;
+---------+------+------------+
| chinese | math | english+10 |
+---------+------+------------+
|      78 |   98 |         69 |
|      76 |   99 |         45 |
+---------+------+------------+
2 rows in set (0.00 sec)

3.3.3 Expression contains multiple fields 

The expression contains multiple fields, and we generally use this query method when we want to sum all the data in a table. If I request the sum of all data in the grades table:

mysql> select chinese,math,english,chinese+math+english from grades;
+---------+------+---------+----------------------+
| chinese | math | english | chinese+math+english |
+---------+------+---------+----------------------+
|      78 |   98 |      59 |                  235 |
|      76 |   99 |      35 |                  210 |
+---------+------+---------+----------------------+
2 rows in set (0.00 sec)

As we can see, the only downside to the convenience of such a query is that the column names are too long. So we have another sql statement that can alias this lengthy column name to simplify it. For details, please see below:


Aliases from 3.4

The syntax we use for aliasing is expression or column name as alias; for example, I alias the lengthy Chinese+math+english above to sum:

mysql> select chinese,math,english,chinese+math+english as sum from grades;
+---------+------+---------+------+
| chinese | math | english | sum  |
+---------+------+---------+------+
|      78 |   98 |      59 |  235 |
|      76 |   99 |      35 |  210 |
+---------+------+---------+------+
2 rows in set (0.00 sec)

Of course it is also possible to alias a single column:

mysql> select chinese as '中文' from grades;
+------+
| 中文 |
+------+
|   78 |
|   76 |
+------+
2 rows in set (0.00 sec)

In this way, it will not be too awkward to look at some fields when we query data. This is the operation of aliasing. Note that as can be omitted but it is recommended to add it for the readability of the code!


3.5distinct (deduplication)

Create a students table:

mysql> create table students(
    -> id int,
    -> name varchar(20),
    -> chinese int,
    -> math int,
    -> english int);
Query OK, 0 rows affected (0.02 sec)

Insert four rows of data:

mysql>  insert into students(id,name,chinese,math,english) values
    -> (1,'孙悟空',69,89,47),
    -> (2,'沙悟净',77,99,60),
    -> (3,'猪八戒',80,88,50),
    -> (4,'白龙马',69,77,88);
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

We found that the Chinese scores of Sun Wukong and Bailongma are the same. When I want to display the Chinese scores and each score is different, I can use distinct to deduplicate:

mysql> select distinct chinese from students;
+---------+
| chinese |
+---------+
|      69 |
|      77 |
|      80 |
+---------+
3 rows in set (0.01 sec)

We can see that 69 is only displayed once, which is the function of distinct in the table: remove duplicate data. It should be noted that distinct only removes duplicate data when we display it, and the deduplicated data in the actual database has not changed! 


3.6 order by (sorting)


3.6.1 A field is sorted by default

We use the students table to operate. For example, I want to sort by default according to English scores:

mysql> select id,name,chinese,math,english from students order by english;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 孙悟空 |      69 |   89 |      47 |
|    3 | 猪八戒 |      80 |   88 |      50 |
|    2 | 沙悟净 |      77 |   97 |      60 |
|    4 | 白龙马 |      69 |   77 |      88 |
+------+--------+---------+------+---------+
4 rows in set (0.00 sec)

By observation, we found that the default sorting is sorted in ascending order. Then the default sorting syntax is: order by field name; Of course, you can also add the asc field to emphasize that your sorting is in ascending order, which enhances the readability of the code.


3.6.2 Sort a field in descending order

For example, sort according to the descending order of English scores:

mysql> select id,name,chinese,math,english from students order by english desc;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    4 | 白龙马 |      69 |   77 |      88 |
|    2 | 沙悟净 |      77 |   97 |      60 |
|    3 | 猪八戒 |      80 |   88 |      50 |
|    1 | 孙悟空 |      69 |   89 |      47 |
+------+--------+---------+------+---------+
4 rows in set (0.00 sec)

It is observed that if we want to sort in descending order, we only need to add the desc keyword after the field name, so the descending sorting syntax is: order by field name desc;


3.6.3 Sorting using expressions and aliases

Use expressions to query, and the sum of the three scores other than the number of query words is sorted in descending order:

mysql> select id,name,chinese + math + english as sum from students order by chinese + math + english desc;
+------+--------+------+
| id   | name   | sum  |
+------+--------+------+
|    2 | 沙悟净 |  234 |
|    4 | 白龙马 |  234 |
|    3 | 猪八戒 |  218 |
|    1 | 孙悟空 |  205 |
+------+--------+------+
4 rows in set (0.00 sec)

 Use an alias to query, and the sum of the three scores other than the number of query words will be sorted in descending order:

mysql>  select id,name,chinese + math + english as sum from students order by sum desc;
+------+--------+------+
| id   | name   | sum  |
+------+--------+------+
|    2 | 沙悟净 |  234 |
|    4 | 白龙马 |  234 |
|    3 | 猪八戒 |  218 |
|    1 | 孙悟空 |  205 |
+------+--------+------+
4 rows in set (0.00 sec)

We found that the results of the above two queries are the same, so if you have a type of operation in the future, you can use any of them to query.


3.6.4 Sorting multiple fields

For example, query in descending order of Chinese and ascending order of mathematics:

mysql> select id,name,chinese,math,english from students order by chinese desc,math;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    3 | 猪八戒 |      80 |   88 |      50 |
|    2 | 沙悟净 |      77 |   97 |      60 |
|    4 | 白龙马 |      69 |   77 |      88 |
|    1 | 孙悟空 |      69 |   89 |      47 |
+------+--------+---------+------+---------+
4 rows in set (0.00 sec)

This kind of operation is suitable for mixed sorting, specific functions and specific operations. Everyone chooses their own sql statement according to their own needs.


3.7where (condition query)

The statement used in the conditional query is where , and its grammatical format is: select field 1, field 2,... where query condition;


3.7.1 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 .. ADN .. Between .. and .., front closed and back closed
IN() exist
IS NULL is empty
IS NOT NULL not empty
LIKE Fuzzy query, when LIKE is followed by a % sign, it represents 0 or more fields, when LIKE is followed by _, the fields are represented according to the number of _.

Find students who failed English:

mysql> select id,name,chinese,math,english from students where english<60;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 孙悟空 |      69 |   89 |      47 |
|    3 | 猪八戒 |      80 |   88 |      50 |
+------+--------+---------+------+---------+
2 rows in set (0.00 sec)

Find students with English scores between 60 and 90: 

mysql> select id,name from students where english between 60 and 90;
+------+--------+
| id   | name   |
+------+--------+
|    2 | 沙悟净 |
|    4 | 白龙马 |
+------+--------+
2 rows in set (0.01 sec)

Find students with the surname Sun:

mysql> select id,name from students where name like '孙%';
+------+--------+
| id   | name   |
+------+--------+
|    1 | 孙悟空 |
+------+--------+
1 row in set (0.00 sec)

Find students whose surname is Sun and whose name length is 2:

mysql> select id,name from students where name like'孙_';
Empty set (0.00 sec)

In the above code, it finally shows that Empty means that there are no students matching this field. Then, many operations in the above table are similar, so the blogger will give three examples here, and you can test it yourself against the table. 


3.7.2 Logical operators

operator illustrate
AND Multiple conditions must be TRUE for the result to be TRUE
OR If any condition is TRUE, the result is TRUE
NOT Condition is TRUE, result is FALSE

 Query the students whose Chinese score>=80 and English score>=80:

mysql> select id,name from students where chinese>= 80 and math>=80;
+------+--------+
| id   | name   |
+------+--------+
|    3 | 猪八戒 |
+------+--------+
1 row in set (0.00 sec)

Query for students whose Chinese score is >80 or English score is <60: 

mysql> select id,name from students where chinese>80 or english<60;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 孙悟空 |
|    3 | 猪八戒 |
+------+--------+
2 rows in set (0.00 sec)

Query students who failed in English:

mysql> select id,name from students where not english>=60;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 孙悟空 |
|    3 | 猪八戒 |
+------+--------+
2 rows in set (0.00 sec)

We can see that the query by logical operators is consistent with the expression of operators such as && and || in C and Java, except that English is used in MySQL.


3.8limit (pagination)

Paging query is to query the corresponding data according to the regulations. This regulation is determined according to your needs, that is, which page or rows of data you want to query. Its grammatical format is to add a limit statement on the basis of the specified column query, and there are three formats:

-- The starting subscript is 0

-- Starting from 0, filter n results

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

-- Starting from s, filter n results

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

-- Starting from s, filter n results, which is more specific than the second usage, it is recommended to use

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

Query the id and name information in the first three records of the students table, and I can add limit 3 at the end:

mysql> select id,name from students limit 3;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 孙悟空 |
|    2 | 沙悟净 |
|    3 | 猪八戒 |
+------+--------+
3 rows in set (0.00 sec)

You can also specify which row to start the query. For example, I want to query from the third row of the students table, and query two rows of records:

mysql> select id,name from students limit 2,2;
+------+--------+
| id   | name   |
+------+--------+
|    3 | 猪八戒 |
|    4 | 白龙马 |
+------+--------+
2 rows in set (0.00 sec)

We see that the effect I want is achieved, so the pagination query syntax for specifying the number of rows is: limit n,s; where s is the starting position, and n is the number of rows . But this method is not rigorous enough, the correct one should be limit n offset s; where s is also the starting position, and n is the number of rows . Note that the number of rows is auto-incremented based on 0 for the first piece of data, which is consistent with the subscript of the array.


4. Modify data

To modify data, the sql statement used is update . Its syntax is: update table name set modify value where condition; for example, set the English score of Zhu Bajie in the students table to 0:

mysql> update students set english = 0 where name = '猪八戒';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Let's check all the information of the students table through the full column query:

We can see that Zhu Bajie's English score has been set to 0. Of course, we can also modify data through expressions. For example, the English score of Zhu Bajie is increased by 100 through the expression:

mysql> update students set english = english+100 where name = '猪八戒';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

We can see that modification through expressions is also possible, but the only thing to pay attention to is. If we want to increase or decrease a piece of data, we should write it as data = data + value, not as data + = value, which is the same as chinese = chinese + 100 in the above code;


5. Delete data

The sql statement used to delete data is delete, and its grammatical format is: delete from table name where delete target; for example, delete the white dragon horse information in the students table:

mysql> delete from students where name = '白龙马';
Query OK, 1 row affected (0.00 sec)

Display the students table:

We can see that there are three records left in the students table. Of course, we can also delete the information of the entire table through delete:

Query OK, 3 rows affected (0.01 sec)

mysql> select * from students;
Empty set (0.00 sec)

After deleting the entire table information of students, it is displayed as empty when we use the full column query. Note that delete only deletes all the data in the table without deleting the table, and the drop operation is more dangerous, it deletes all the table and all the data in the table. Therefore, we must pay attention when deleting the database operation!


The content of the article is relatively rich, and you must practice more after you come down. Only by implementing these operations can we better grasp these knowledge points. In addition, you can also test the examples that are not mentioned in the comparison operators in the where conditional query. This blog post is over here, thank you for your patience in reading, if you gain something, please pay attention.

Guess you like

Origin blog.csdn.net/weixin_64916311/article/details/130004309