MySQL - table addition, deletion, query and modification

Table of contents

1.Create

1. Single row of data + full column insertion

2.Multiple rows of data + specified column insertion

3. Insert otherwise update

4. Replacement

2.Retrieve (read)

1. select column query

2.Where conditions

3. Sorting of results

4. Filter paging results

3.Update (modification)

4.Delete

1. Delete data

2. Delete the entire table data

3. Truncate table

4. Remove duplicate table data

5. Aggregation function

6. Use of group by clause 


1.Create

grammar:

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

Case:

Create a student table:

mysql> create table students(
    -> id int unsigned primary key auto_increment,
    -> name varchar(20) not null,
    -> qq varchar(20) not null
    -> );

 1. Single row of data + full column insertion

To insert two records, the number of value_list must be consistent with the number and order of the columns that define the table.
Note that when inserting, you do not need to specify the id (of course, you need to explicitly insert data into those columns at that time), then mysql will Use the default value for auto-increment.

Specify insert:

 Insert full column:

2.Multiple rows of data + specified column insertion

To insert two records, the number of value_list must be consistent with the number and order of the specified columns:

mysql> insert into students (name,qq) values 
    -> ('孙仲谋','65988135'),
    -> ('曹孟德','974623215'),
    -> ('刘玄德','948735415');

3. Insert otherwise update

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

Synchronous update operation syntax can be selectively performed:

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

Case:

insert students value (100,'八戒','100100100') on duplicate key update name='项羽(-_-)',qq='110110110';

Explanation: Query OK, 2 rows affected (0.00 sec)

  • -- 0 row affected: There is conflicting data in the table, but the value of the conflicting data is equal to the value of update
  • -- 1 row affected: There is no conflicting data in the table, the data is inserted
  • -- 2 row affected: There is conflicting data in the table, and the data has been updated

Get the number of affected data rows through the MySQL function:

SELECT ROW_COUNT();

4. Replacement

-- If the primary key or unique key does not conflict, insert it directly;
-- If the primary key or unique key conflicts, delete it and then insert it;

replace into students value(100,'八戒','100100100');

-- 1 row affected: There is no conflicting data in the table, the data is inserted
-- 2 row affected: There is conflicting data in the table, the data is deleted and reinserted 

2.Retrieve (read)

grammar:

SELECT
[DISTINCT] {* | {column [, column] ...}
[FROM table_name]
[WHERE ...]
[ORDER BY column [ASC | DESC], ...]
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);
Query OK, 7 rows affected (0.00 sec)
Records: 7 Duplicates: 0 Warnings: 0

1. select column query

Full column query :

-- Normally it is not recommended to use * for full column query:

  1. The more columns you query, the greater the amount of data that needs to be transferred;
  2. It may affect the use of indexes. (The index will be explained in later courses)
select * from exam_result;

Specify column query:

select id,name,english from exam_result;

The query field is an expression:

Ten points will be added to math scores:

select id ,name,math+10 from exam_result;

Calculate the total score:

Specify an alias for query results

Calculate the total score and change the alias to 'total score':

select id ,name,chinese+math+english 总分 from exam_result;

The result is deduplicated:

select distinct math from exam_result;

 2.Where conditions

Comparison operators:

operator

illustrate

>, >=,

Greater than, greater than or equal to, less than, less than or equal to

=

Equal to, NULL is not safe, for example, the result of NULL = NULL is NULL

<=>

Equal to, NULL is safe, for example, NULL The result of NULL is TRUE(1)

!=, <>

not equal to

BETWEEN a0 AND a1

Range match, [a0, a1], if a0

IN (option, ...)

If it is any one of the options, return TRUE(1)

IS NULL

is NULL

IS NOT NULL

Not NULL

LIKE

Fuzzy matching. % represents any number (including 0) of any character; _ represents any character

Logical Operators:

operator

illustrate

AND

Multiple conditions must all be TRUE(1), and the result is TRUE(1)

OR

If any condition is TRUE(1), the result is TRUE(1)

NOT

The condition is TRUE(1), the result is FALSE(0)

Case: 

Students who failed in English have English scores (< 60):

select id,name,english from exam_result where english<60;

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

method one:

select id,name,chinese from exam_result where chinese>=80 and chinese<=90;

Method Two:

select id,name,chinese from exam_result where chinese between 80 and 90;

Students with math scores of 58 or 59 or 98 or 99 and their math scores:

method one:

select id,name,math from exam_result where math=58 or math=65 or math=99 or math=98;

Method Two:

select id,name,math from exam_result where math in (58,65,99,98);

Classmates named Sun and classmates named Sun:

Classmates surnamed Sun include Sun XX and Sun XX:

select id,name from exam_result where name like '孙%';

 Classmate Sun has only two characters in his name:

select id,name from exam_result where name like '孙_';

Students whose Chinese scores are better than their English scores:

select id,name,chinese,math from exam_result where chinese>math;

Students whose total score is below 200 points:

Note: Expressions are used in WHERE conditions, aliases cannot be used in WHERE conditions.

select id,name,chinese+math+english total from exam_result where chinese+math+english <200;

Why can't aliases be used in WHERE conditions?

The above SQL statement includes two parts: select and where. Since the where statement has a higher priority than the select statement, the distinction does not take effect in where.

Students whose Chinese score is >80 and whose surname is not Sun:

select id,name,chinese from exam_result where chinese>80 and  name not like '孙%';

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

select name,chinese,math,english,chinese+math+english total from exam_result where name like '孙_' or (chinese+math+english>200 and chinese < math and english > 80);

NULL query

select id,name,qq from exam_result where qq is not null;
select id,name,qq from exam_result where qq is null;

Comparison between NULL and NULL, the difference between = and <=>:

3. Sorting of results

grammar:

-- ASC is ascending order (from small to large)
-- DESC is descending order (from large to small)
-- The default is ASC

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

Note: For queries without an ORDER BY clause, the order returned is undefined and should never be relied upon.

Case:

Classmates and math scores are displayed in ascending order of math scores:

select id,name,math from exam_result order by math;
select id,name,math from exam_result order by  math asc;

Classmates and math scores are displayed in descending order of math scores:

select id,name,math from exam_result order by  math desc;

 Classmates and QQ numbers are displayed sorted by QQ numbers:

select id,name,qq from exam_result order by qq desc;

Note: NULL is considered smaller than any value and appears at the bottom in descending order.

Query the scores of students in each subject, and display them in descending order of mathematics, ascending order of English, and ascending order of Chinese:

select name,chinese,math,english from exam_result order by math desc , english asc ,chinese asc;

Query classmates and total scores, from high to low:

Expressions can be used in order by.

select name,chinese+math+english total from exam_result order by chinese+math+english desc;
select name,chinese+math+english total from exam_result order by total desc;

The reason why aliases can be used in order by is that the priority of the order SQL statement is smaller than the priority of select. The results are filtered out first and then sorted.

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

select name,math from exam_result where name like '孙%' or name like '曹%' order by math desc;

4. Filter paging results

grammar:

-- 起始下标为 0
-- 从 s 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT s, n
-- 从 0 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n;
;
-- 从 s 开始,筛选 n 条结果,比第二种用法更明确,建议使用
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.

Case:

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

select id,name,chinese,math,english from exam_result order by id limit 3 offset 0;
select id,name,chinese,math,english from exam_result order by id limit 3 offset 3;
select id,name,chinese,math,english from exam_result order by id limit 3 offset 6;

3.Update (modification)

grammar:

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

Update the column values ​​of the 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 exam_result set math=math+30 order by chinese+math+english limit 3 ;

  Update the Chinese scores of all students to twice the original value:

update exam_result set chinese=chinese*2 ;

4.Delete

1. Delete data

grammar:

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

Case:

Delete Sun Wukong’s test scores:

delete from exam_result where name='孙悟空';

2. Delete the entire table data

Note: Use caution when deleting the entire table! ! ! !

test:

Delete the entire table:

 Insert data again:

We found that the id, auto_increment, will still increase.

3. 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. Will reset the AUTO_INCREMENT item

Case:

Truncate table:

Insert data again:

Found: AUTO_INCREMENT will be counted again.

4. Remove duplicate table data

data preparation:

step:

  1. Create a table with the same size as the original table
  2. Insert data from the original table into the new table
  3. Rename the original table and rename the new table to the name of the original table

5. Aggregation function

function

illustrate

COUNT([DISTINCT] expr)

Returns the number of queried data

SUM([DISTINCT] expr)

Returns the sum of the queried data. It is meaningless if it is not a number.

AVG([DISTINCT] expr)

Returns the average value of the queried data. It is meaningless if it is not a number.

MAX([DISTINCT] expr)

Returns the maximum value of the queried data. It is meaningless if it is not a number.

MIN([DISTINCT] expr)

Returns the minimum value of the queried data. It is meaningless if it is not a number.

 Count how many students there are in the class:

 Count the QQ numbers of classmates in the class:

NULL is not included in the result.

Count the number of math scores in this exam:

 Total Statistics Mathematics Score:

Statistical average total score:

 Return the highest score in English:

Returns minimum math score >70 points:

6. Use of group by clause 

Use the group by clause in select to perform a group query on the specified column:

select column1, column2, .. from table group by column;

Preparation, create an employee information table (classic test table from oracle 9i)

  1. EMP employee list
  2. DEPT department table
  3. SALGRADE salary scale

 Database file   scott_data.sql file  extraction code wqwq.

This is a sql database backup file that can be restored directly to mysql using source.

 How to display the average and maximum salary for each department:

Shows the average and minimum wages for each position in each department:

Show the departments with an average salary below 2000 and its average salary:

Use having for conditional filtering when grouping queries:

 --having is often used in conjunction with group by. Its function is to filter groups, and its function is somewhat like where.

Guess you like

Origin blog.csdn.net/qq_63943454/article/details/135046037