【MySql】Basic query


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

Create a table first:

mysql> create table students (
    -> id int unsigned primary key auto_increment,
    -> sn int unsigned unique key,
    -> name varchar(20) not null,
    -> qq varchar(32) unique key
    -> );
Query OK, 0 rows affected (0.26 sec)

insert operation insert

-- 指定列插入
mysql> insert into students (sn,name,qq) values (123,'张三','456789');
Query OK, 1 row affected (0.03 sec)

-- 全列插入
mysql> insert into students values (10,124,'关羽','123456');
Query OK, 1 row affected (0.04 sec)

-- 多行插入
mysql> insert into students values (13,127,'王五','14678909'),(14,128,'赵七','567890'),(15,129,'陈九','7890123');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

Of course, the insertion fails because the value corresponding to the primary key or unique key already exists

Optional synchronous update operation syntax:

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

image-20230612190626621

mysql> insert into students values (13,132,'许攸','111111') on duplicate key update sn=132,name='xuyyou',qq='1111';
Query OK, 2 rows affected (0.04 sec)


-- 0 row affected: 表中有冲突数据,但冲突数据的值和 update 的值相等
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,并且数据已经被更新

A primary key conflict occurs and an insert operation is changed to an update operation

replace

-- 主键 或者 唯一键 没有冲突,则直接插入;
-- 主键 或者 唯一键 如果冲突,则删除后再插入
mysql> replace into students (sn,name,qq) values (140,'许攸','34567812');
Query OK, 1 row affected (0.03 sec)
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,删除后重新插入

Query operation select

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

Create a table:

-- 创建表结构
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);

select query

full column query

image-20230612194518939

-- 通常情况下不建议使用 * 进行全列查询
-- 1. 查询的列越多,意味着需要传输的数据量越大;
-- 2. 可能会影响到索引的使用。

Specified column query

-- 指定列的顺序不需要按定义表的顺序来
SELECT id, name, english FROM exam_result;

image-20230612194726928

The query field is an expression

-- 表达式不包含字段
SELECT id, name, 10 FROM exam_result;

image-20230612195259892

-- 表达式包含多个字段
SELECT name,math, chinese + math + english FROM exam_result;

image-20230612195502482

Specify an alias for query results

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

For example, our query name above is too long, just add as:

image-20230612195601375

Of course, the following is also possible:

image-20230612195741439

Result deduplication distinct

select distinct math from exam_result;

image-20230612200152730

Where condition judgment

Comparison operators:

运算符 									说明
>, >=, <, <= 						大于,大于等于,小于,小于等于
= 									等于,NULL 不安全,例如 NULL = NULL 的结果是 NULL
<=>									等于,NULL 安全,例如 NULL <=> NULL 的结果是 TRUE(1)
!=, <> 								不等于
BETWEEN a0 AND a1 					范围匹配,[a0, a1],如果 a0 <= value <= a1,返回 TRUE(1)
IN (option, ...) 					如果是 option 中的任意一个,返回 TRUE(1)
IS NULL 							是 NULL
IS NOT NULL 						不是 NULL
LIKE 								模糊匹配。% 表示任意多个(包括 0 个)任意字符;_ 表示任意一个字符

Logical Operators:

运算符 						说明
AND 				多个条件必须都为 TRUE(1),结果才是 TRUE(1)
OR 					任意一个条件为 TRUE(1), 结果为 TRUE(1)
NOT					条件为 TRUE(1),结果为 FALSE(0)

Here are some examples to practice with:

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

image-20230612201151019

  • Students with Chinese scores in [80, 90] and their Chinese scores
select name,chinese from exam_result where chinese>=80 and chinese<=90;

image-20230612201333958

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

image-20230612201447761

  • 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;

image-20230612201639111

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

image-20230612201751705

  • A classmate surnamed Sun and a classmate named Sun
select name from exam_result where name like '孙%';

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

image-20230612202256140

  • Students whose Chinese scores are better than their English scores
select name,chinese,english from exam_result where chinese > english;

image-20230612202402744

  • Students with a total score of 200 or less
select name,chinese+english+math from exam_result where chinese+english+math<200;

image-20230612202657562

Note: It is wrong to write the following:

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

This is due to the impact of the execution order of sql: the execution order here is very important, and aliases cannot be used here. It is very simple: this is because the from is executed first, and which table to filter the data from first. When filtering, the filter conditions must be set first

image-20230612203353738

Of course, the following is also wrong: you cannot rename in the filter condition

image-20230612203623043

  • Students whose Chinese score is > 80 and whose surname is not Sun
select name,chinese from exam_result where chinese >80 and name not like '孙%';

image-20230612203919113

  • Student Sun, otherwise the total score > 200 and the Chinese score < the math score and the English score > 80
select name,chinese,math,english,chinese+math+english 总分 from exam_result where name like'孙_' or  (chinese+math+english>200 and chinese < math and english>80);

image-20230612204322235

  • query for NULL

To demonstrate, first create a table test:

image-20230612204712628

select * from test where name is null;

image-20230612204745578

order bysort

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

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

Below, some cases are used to understand order by sorting:

  • Classmates and math scores, displayed in ascending order of math scores
 select name,math from exam_result order by math asc;

image-20230612205303662

  • Classmates sorted
-- NULL 视为比任何值都小,升序出现在最上面

image-20230612205532311

  • Query students' scores in various subjects, and display them in descending order of mathematics, ascending order of English, and ascending order of Chinese
select name,math,english,chinese from exam_result order by math desc,english asc,chinese asc

image-20230612205902228

Note: order by defaults to ascending asc sorting

  • Query classmates and total scores, from low to high
select name,math+chinese+english as total from exam_result order by total;

image-20230612210207058

Why can aliases be used again? Aliases cannot be used after where, why is order by sorting possible here?

To sort the data in the table structure, there must be data first, and then sort it.

insert image description here

  • Query the math scores of students surnamed Sun or students surnamed Cao, and the results are displayed in descending order of math scores
select name,math from exam_result where name like '孙%' or name like '曹%' order by math desc;

image-20230614105603234

limit filter paging results

-- 起始下标为 0
-- 从 s 开始(下标从0开始),筛选 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;

image-20230614110244193

image-20230614110109012

It needs to be sorted by data. Only when the data is ready, you have to display it. The essential function of limit is to "display"

Update operation update

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

Update the column value of the query result

  • Change the math score of Sun Wukong to 80 points
update exam_result set math=80 where name='孙悟空';

image-20230614111325331

  • 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='曹孟德';

image-20230614111704366

  • Add 30 points to the mathematics scores of the three students with the bottom three total scores
 select name,math+chinese+english total from exam_result order by total asc limit 3;

image-20230614122933070

  • Update the Chinese scores of all students to double the original
update exam_result set chinese=chinese*2;

image-20230614123447406

Delete operation delete

DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]
  • Delete the test scores of Sun Wukong
delete from exam_result wherename='孙悟空';

image-20230614123917746

  • Delete the entire table data
-- 准备测试表
CREATE TABLE for_delete (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20)
);
Query OK, 0 rows affected (0.16 sec)
-- 插入测试数据
INSERT INTO for_delete (name) VALUES ('A'), ('B'), ('C');


-- 删除整表数据
DELETE FROM for_delete;

-- 查看删除结果
SELECT * FROM for_delete;
Empty set (0.00 sec)

-- 再插入一条数据,自增 id 在原值上增长
INSERT INTO for_delete (name) VALUES ('D');
  • truncate table
  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, but TRUNCATE does not go through real things when deleting data, so it cannot be rolled back
  3. Will reset AUTO_INCREMENT items
TRUNCATE [TABLE] table_name

for example:

-- 准备测试表
CREATE TABLE for_truncate (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20)
);

-- 插入测试数据
INSERT INTO for_truncate (name) VALUES ('A'), ('B'), ('C');

-- 截断整表数据,注意影响行数是 0,所以实际上没有对数据真正操作
TRUNCATE for_truncate;

image-20230614125301516

-- 再插入一条数据,自增 id 在重新增长
INSERT INTO for_truncate (name) VALUES ('E');

image-20230614125342791

-- 查看表结构,会有 AUTO_INCREMENT=2 项
SHOW CREATE TABLE for_truncate\G

image-20230614125423155

insert query result

INSERT INTO table_name [(column [, column ...])] SELECT ...
  • Delete duplicate records in the table, there can only be one copy of duplicate data
-- 创建原数据表
CREATE TABLE duplicate_table (id int, name varchar(20));

-- 插入测试数据
INSERT INTO duplicate_table VALUES
(100, 'aaa'),
(100, 'aaa'),
(200, 'bbb'),
(200, 'bbb'),
(200, 'bbb'),
(300, 'ccc');

image-20230614172612701

-- 创建一张空表 no_duplicate_table,结构和 duplicate_table 一样
CREATE TABLE no_duplicate_table LIKE duplicate_table;
-- 将 duplicate_table 的去重数据插入到 no_duplicate_table
INSERT INTO no_duplicate_table SELECT DISTINCT * FROM duplicate_table;
-- 通过重命名表,实现原子的去重操作
RENAME TABLE duplicate_table TO old_duplicate_table,
no_duplicate_table TO duplicate_table;
-- 查看最终结果
SELECT * FROM duplicate_table;

image-20230614184618308

Why will the model be renamed in the future: I just want to wait until everything is ready, and then put it in, update it, take effect, etc.

Guess you like

Origin blog.csdn.net/weixin_60478154/article/details/131214014