[MySQL] Addition, deletion and modification of basic query tables


CRUD : Create (create), Retrieve (read), Update (update), Delete (delete)

1. Insertion operation----insert

Create user table and set four fields

mysql> create table user(
    -> id int unsigned primary key auto_increment,
    -> sn int unsigned unique key,
    -> name varchar(20) not null,
    -> tel varchar(11) unique key
    -> );

insert image description here

1.1 Simple Insertion

--指定列插入--
mysql> insert into user (id,sn,name) values(1,200,'刘邦');
Query OK, 1 row affected (0.01 sec)
--全列插入--
mysql> insert into user values(2,201,'刘倍','1111111');
Query OK, 1 row affected (0.01 sec)
--全列多行插入--
mysql> insert into user values(3,202,'刘某','000010'),(4,203,'王某','220');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0
--指定列多行插入--
mysql> insert into user (sn,name,tel) values(300,'刘某','999'),(303,'王某','888');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

Note: insert into can be omitted as insert

1.2 Whether to update when inserting ----ON DUPLICATE KEY UPDATE

Insertion fails because the value corresponding to the primary key or unique key already exists, and the synchronous update operation can be selectively performed

mysql> insert into user values(2,201,'刘倍','1110111');
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
mysql> insert into user values(11,201,'刘倍','1111111');
ERROR 1062 (23000): Duplicate entry '201' for key 'sn'
mysql> 
INSERT ... ON DUPLICATE KEY UPDATE
column = value [, column = value] ...

insert image description here

insert into user values(2,201,'刘倍','1110111')on duplicate key update sn=20,name='刘备',tel='2222';
Query OK, 2 rows affected (0.01 sec)
-- 0 row affected: 表中有冲突数据,但冲突数据的值和 update 的值相等
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,并且数据已经被更新

Note: The updated data cannot conflict with other data

1.3 Replace when inserting ----REPLACE

-- 主键 或者 唯一键 没有冲突,则直接插入;
-- 主键 或者 唯一键 如果冲突,则删除后再插入
mysql> replace into user(sn,name,tel)values(666,'xiaohaizi','1111111');
Query OK, 2 rows affected (0.00 sec)
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,删除后重新插入

2. Query - select

Create a data table and add data

mysql> 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 '英语成绩'
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> 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);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

2.1 Simple query and deduplication

--全列查询
mysql> select * from exam_result;
--指定列查询
mysql> select name from exam_result;

The query field is an expression

-- 表达式不包含字段会在结果后面拼接上
SELECT id, name, 10 FROM exam_result;

Aliasing query results

SELECT column [AS] alias_name [...] FROM table_name;
如:
select chinese+math+english as total from exam_result;

Result deduplication

select distinct math from exam_result;

2.2 Basic query----where condition

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. % represents any number (including 0) of any character; _ represents any one character

Conditional Operators: same and or not

operator illustrate
AND Multiple conditions must all be TRUE (1) for the result to be TRUE (1)
OR Any condition is TRUE(1), the result is TRUE(1)
NOT Condition is TRUE (1), result is FALSE (0)

2.2.3 Case demonstration

  • Students who fail in English and their English scores ( < 60 )
select name,english from exam_result where english<60;

insert image description here

  • Students with Chinese scores in [80, 90] and their Chinese scores
mysql> select name,chinese from exam_result where chinese>=80 and chinese<=90;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 孙悟空    |      87 |
| 猪悟能    |      88 |
| 曹孟德    |      82 |
+-----------+---------+
或者
mysql> select name,chinese from exam_result where chinese between 80 and 90;
  • Students whose math scores are 58 or 59 or 98 or 99 and their math scores
select name,math from exam_result where math=58 or math=59 or math=98 or math=99;
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    |   98 |
| 猪悟能    |   98 |
+-----------+------+
或者:
select name,math from exam_result where math in(58,59,98,99);
  • A classmate surnamed Sun and a classmate named Sun
mysql> select name from exam_result where name like '孙%';
+-----------+
| name      |
+-----------+
| 孙悟空    |
| 孙权      |
+-----------+
2 rows in set (0.00 sec)

mysql> select name from exam_result where name like '孙_';
+--------+
| name   |
+--------+
| 孙权   |
+--------+
  • Students whose Chinese scores are better than their English scores
 select name,chinese,english from exam_result where chinese>english;
+-----------+---------+---------+
| name      | chinese | english |
+-----------+---------+---------+
| 唐三藏    |      67 |      56 |
| 孙悟空    |      87 |      77 |
| 曹孟德    |      82 |      67 |
| 刘玄德    |      55 |      45 |
| 宋公明    |      75 |      30 |
+-----------+---------+---------+

  • Students with a total score of 200 or less
select name,chinese+math+english as total from exam_result where chinese+math+english<200;
+-----------+-------+
| name      | total |
+-----------+-------+
| 刘玄德    |   185 |
| 宋公明    |   170 |
+-----------+-------+

Note: Due to the order of execution, an error will be reported if written in the following way

select name,chinese+english+math total from exam_result where total<200;
ERROR 1054 (42S22): Unknown column 'total' in 'where clause'

insert image description here

  • Students whose Chinese score is greater than 80 and whose surname is not Sun
select name,chinese from exam_result where chinese>80 and name not like '孙%';
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 猪悟能    |      88 |
| 曹孟德    |      82 |
+-----------+---------+
  • Student Sun, otherwise the total score should be > 200 and the Chinese score should be < the math score and the English score should be > 80
select name,chinese,math,english,chinese+math+english total from exam_result where name like '孙_' or
+-----------+---------+------+---------+-------+
| name      | chinese | math | english | total |
+-----------+---------+------+---------+-------+
| 猪悟能    |      88 |   98 |      90 |   276 |
| 孙权      |      70 |   73 |      78 |   221 |
+-----------+---------+------+---------+-------+
  • NULL query
mysql> select * from exam_result where name is null;
Empty set (0.00 sec)

2.4 Sorting----order by

-- ASC 为升序(从小到大)默认为升序
-- DESC 为降序(从大到小)
-- 默认为 ASC
SELECT ... FROM table_name [WHERE ...]
ORDER BY column [ASC|DESC], [...];

Classmates' names and math grades, displayed in ascending order of math grades

select name,math from exam_result order by math asc;
+-----------+------+
| name      | math |
+-----------+------+
| 宋公明    |   65 |
| 孙权      |   73 |
| 孙悟空    |   78 |
| 曹孟德    |   84 |
| 刘玄德    |   85 |
| 唐三藏    |   98 |
| 猪悟能    |   98 |
+-----------+------+

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

mysql> select name,math,english,chinese from exam_result order by math desc,english desc,chinese asc;
+-----------+------+---------+---------+
| name      | math | english | chinese |
+-----------+------+---------+---------+
| 猪悟能    |   98 |      90 |      88 |
| 唐三藏    |   98 |      56 |      67 |
| 刘玄德    |   85 |      45 |      55 |
| 曹孟德    |   84 |      67 |      82 |
| 孙悟空    |   78 |      77 |      87 |
| 孙权      |   73 |      78 |      70 |
| 宋公明    |   65 |      30 |      75 |
+-----------+------+---------+---------+

Note: The sorting status here is descending order of mathematics > ascending order of English > ascending order of Chinese.
Query the mathematics scores of students surnamed Sun or students surnamed Cao, and the results are displayed in descending order of mathematics scores

mysql> select name,math from exam_result where name like '孙%' or name like '曹%' order by math desc;
+-----------+------+
| name      | math |
+-----------+------+
| 曹孟德    |   84 |
| 孙悟空    |   78 |
| 孙权      |   73 |
+-----------+------+

Execution order
insert image description here
to query classmates and total scores, sorting from low to high
is performed after obtaining data, so this is different from where, you can use aliases

select name,math+chinese+english as total from exam_result order by total;
+-----------+-------+
| name      | total |
+-----------+-------+
| 宋公明    |   170 |
| 刘玄德    |   185 |
| 唐三藏    |   221 |
| 孙权      |   221 |
| 曹孟德    |   233 |
| 孙悟空    |   242 |
| 猪悟能    |   276 |
+-----------+-------+

limit filter paging results

– The starting subscript of data display is 0
– Start from s (subscript starts from 0), filter n results
SELECT … FROM table_name [WHERE …] [ORDER BY …] LIMIT s, n – – start from
0
, filter n results
SELECT … FROM table_name [WHERE …] [ORDER BY …] LIMIT n;

– start from s, filter n results, compared to the second usage To be more explicit, it is recommended to use
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n OFFSET s;
start at position s, offset by n positions

mysql> select * from exam_result limit 3;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |      67 |   98 |      56 |
|  2 | 孙悟空    |      87 |   78 |      77 |
|  3 | 猪悟能    |      88 |   98 |      90 |
+----+-----------+---------+------+---------+
3 rows in set (0.00 sec)

mysql> select * from exam_result limit 1,3;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  2 | 孙悟空    |      87 |   78 |      77 |
|  3 | 猪悟能    |      88 |   98 |      90 |
|  4 | 曹孟德    |      82 |   84 |      67 |
+----+-----------+---------+------+---------+
3 rows in set (0.00 sec)

mysql> select * from exam_result limit 3 offset 0;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |      67 |   98 |      56 |
|  2 | 孙悟空    |      87 |   78 |      77 |
|  3 | 猪悟能    |      88 |   98 |      90 |
+----+-----------+---------+------+---------+
3 rows in set (0.00 sec)

3. Modify operation ----update

UPDATE table_name SET column = expr [, column = expr ...]
[WHERE ...] [ORDER BY ...] [LIMIT ...]

Change the math score of Sun Wukong to 80 points

mysql> update exam_result set math=80 where name='孙悟空';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
mysql> select name,math from exam_result;
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    |   98 |
| 孙悟空    |   80 |
| 猪悟能    |   98 |
| 曹孟德    |   84 |
| 刘玄德    |   85 |
| 孙权      |   73 |
| 宋公明    |   65 |
+-----------+------+

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

update exam_result set math=60,chinese=70 where name='曹孟德';
mysql> select name,math,chinese from exam_result;
+-----------+------+---------+
| name      | math | chinese |
+-----------+------+---------+
| 唐三藏    |   98 |      67 |
| 孙悟空    |   80 |      87 |
| 猪悟能    |   98 |      88 |
| 曹孟德    |   60 |      70 |
| 刘玄德    |   85 |      55 |
| 孙权      |   73 |      70 |
| 宋公明    |   65 |      75 |
+-----------+------+---------+

Add 30 points to the mathematics scores of the top three students with the lowest total scores
Note: When updating here, limit 0,3 cannot be used

mysql> select name,math+chinese+english total from exam_result order by total limit 0,3;
+-----------+-------+
| name      | total |
+-----------+-------+
| 宋公明    |   170 |
| 刘玄德    |   185 |
| 曹孟德    |   197 |
+-----------+-------+
--update exam_result set math=math+30 order by math+chinese+english asc  limit 0,3;
--ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3' at line 1

mysql> update exam_result set math=math+30 order by math+chinese+english asc  limit 3;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select name,math+chinese+english total from exam_result order by total limit 0,3;
+-----------+-------+
| name      | total |
+-----------+-------+
| 宋公明    |   200 |
| 刘玄德    |   215 |
| 唐三藏    |   221 |
+-----------+-------+
3 rows in set (0.00 sec)

mysql> select name,math+chinese+english total from exam_result order by total;
+-----------+-------+
| name      | total |
+-----------+-------+
| 宋公明    |   200 |
| 刘玄德    |   215 |
| 唐三藏    |   221 |
| 孙权      |   221 |
| 曹孟德    |   227 |
| 孙悟空    |   244 |
| 猪悟能    |   276 |
+-----------+-------+
7 rows in set (0.00 sec)

Update the Chinese scores of all students to double the original

mysql> update exam_result set chinese=chinese*2;
Query OK, 7 rows affected (0.00 sec)
Rows matched: 7  Changed: 7  Warnings: 0

mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |     134 |   98 |      56 |
|  2 | 孙悟空    |     174 |   80 |      77 |
|  3 | 猪悟能    |     176 |   98 |      90 |
|  4 | 曹孟德    |     140 |   90 |      67 |
|  5 | 刘玄德    |     110 |  115 |      45 |
|  6 | 孙权      |     140 |   73 |      78 |
|  7 | 宋公明    |     150 |   95 |      30 |
+----+-----------+---------+------+---------+

Four, delete - delete

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

Delete the test scores of Sun Wukong

mysql> delete from exam_result where name='孙悟空';
Query OK, 1 row affected (0.01 sec)

mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |     134 |   98 |      56 |
|  3 | 猪悟能    |     176 |   98 |      90 |
|  4 | 曹孟德    |     140 |   90 |      67 |
|  5 | 刘玄德    |     110 |  115 |      45 |
|  6 | 孙权      |     140 |   73 |      78 |
|  7 | 宋公明    |     150 |   95 |      30 |
+----+-----------+---------+------+---------+

delete the entire table

mysql> CREATE TABLE for_delete (
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(20)
    -> );

mysql> INSERT INTO for_delete (name) VALUES ('A'), ('B'), ('C');

mysql> select * from for_delete;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+

mysql> delete from for_delete;

mysql> select * from for_delete;

mysql> INSERT INTO for_delete (name) VALUES ('D');

mysql> select * from for_delete;
+----+------+
| id | name |
+----+------+
|  4 | D    |
+----+------+

Note: Deleting the entire table only deletes the data, which belongs to the DML language. After deleting the data in the table, the value of AUTO_INCREMENT will not be reset, and it will continue to increase along the previous data

4.1 Truncated table ----TRUNCATE

  • It can only operate on the entire table, and cannot operate on partial data like DELETE;
  • In fact, MySQL does not operate on data, so it is faster than DELETE, but TRUNCATE does not go through real things when deleting data, so it cannot be rolled back
  • Will reset AUTO_INCREMENT items
TRUNCATE [TABLE] table_name

The test is the same as the above delete

mysql> CREATE TABLE for_truncate (
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(20)
    -> );

mysql> INSERT INTO for_truncate (name) VALUES ('A'), ('B'), ('C');
mysql> select * from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+
mysql> TRUNCATE for_truncate;
mysql> show create table for_truncate\G
*************************** 1. row ***************************
       Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

mysql> INSERT INTO for_truncate (name) VALUES ('D');

mysql> select * from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | D    |
+----+------+
mysql> show create table for_truncate\G
*************************** 1. row ***************************
       Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

4.2 The difference between delete and truncate

The difference between delete operations:

  • The DELETE statement is used to delete data records in a table row by row. It is a transactional operation that can specify conditions at execution time and only delete rows that meet the conditions. DELETE operations can be rolled back, so delete operations on table data can be undone .
    The TRUNCATE statement is used to quickly delete all the data in the table. It is a DDL (Data Definition Language) operation that deletes all rows in the table and does not return deleted rows. TRUNCATE operations cannot be rolled back, so once executed, the data cannot be recovered.

Efficiency and performance:

  • TRUNCATE operations are generally faster than DELETE operations , especially when dealing with large tables. TRUNCATE does not record every delete operation in the log, but records a DDL operation, so it executes faster.
    The DELETE operation will generate corresponding log records in the database log, and may trigger related triggers and constraint checks, so it will be relatively slower than the TRUNCATE operation.

Spaces and indexes:

The DELETE operation only deletes the data rows in the table, but does not release the storage space associated with these rows. This means that if there are a large number of deleted rows in the table, it may cause fragmentation of the storage space.
The TRUNCATE operation will not only delete the data rows in the table, but also release the storage space associated with the table, which will cause the size of the data file to be reduced and the storage space to be emptied.
The DELETE operation will not reset the auto-increment ID value of the table, and the TRUNCATE operation will reset the auto-increment ID value of the table to the initial value.

In summary , both DELETE and TRUNCATE can be used to delete data, but DELETE is more flexible and controllable, you can specify deletion conditions as needed, and you can roll back operations. TRUNCATE is more suitable for quickly deleting the data of the entire table, and the execution speed is faster and more efficient, but the operation cannot be rolled back. Which action you choose to use depends on your specific needs and situation.

Guess you like

Origin blog.csdn.net/m0_54469145/article/details/131556235