MySQL DML advanced, paging search, SQL constraints, multi-table operation learning

  • Xiaojie's mysql database learning essays, the summary and sequel are coming.
  • Xiaojie is new to mysql. If there are many inappropriate expressions or wrong views, I hope that readers can give me corrections, and I hope you can support Xiaojie more.
  • Everyone learns and progresses together in the spirit of mutual learning and common progress. 

The previous article is wonderful

  • Entering MySQL for the first time

A first glimpse of MYSQL database, skilled use of SQL statements, and graphical interface to improve efficiency .net/weixin_53695360/article/details/123481586

  • MySQL detailed knowledge and various query operations are refined

Database statement execution process understanding, storage engine learning, character set understanding, plus various SQL data types understanding introduction plus various SQL data query analysis and topic practice Introduction to understanding various sql data types plus various SQL data query analysis and topic practice https://blog.csdn.net/weixin_53695360/article/details/123571592

1. What is DML, and the basic operations of DML, the update operation of table columns and rows

  • Edit operations on columns

#首先简单的创建一个student表为后序操作做准备
use test;
create table student (
	id int,
	name varchar(8),
	age tinyint
) engine = innodb default charset = utf8mb4;
desc student;
  • Add a new column, format: alter table table name add new column name data type (length);
alter table student add addr varchar(20);
#新增一个addr列出来
  • Modify the data type (length) of the column, format: alter table table name modify column name modified data type (length);
alter table student modify addr varchar(15);
#修改student表中addr列的数据类型 (长度修改)
alter table student modify addr char(20);
#修改student表中addr列的数据类型 (类型修改为char(20))
  • Modify the name of the column, format: alter table table name change column name new column name new column name data type (length);
alter table student change addr stu_addr varchar(20);
# change 相比 modify 而言功能更加强大可以修改列名字. 
# modify不可以修改列名
  • . Delete the specified column, format: alter table table name drop column name;
alter table student drop stu_addr;
# 删除student表中的stu_addr列
  • It is not recommended to use the above modification operations on the column structure of the table, because the databases of many companies are very large, and modifying a column of data is not a trivial matter. If the modification is not good, it will be bad if the data is lost.
  • Various operations on table rows and table records (add, delete, modify, check)

insert table record

  • Method 1, insert into the specified field, the format: insert into table name (field 1, field 2, ...) values ​​(value 1, value 2, ...);              I call this method the insertion of the specified field Operations, fields and assignments should be in one-to-one correspondence
insert into student(id, name, age) values(1000, '张三', 18);
# 向student表中插入一条id 为1000 name 为张三, age 18的记录
insert into student(id, name, age)
values(1001, '李四', 20),
(1002, '王五', 22),
(1003, '胖子', 25);
#还可以支持values后面跟上多条记录
#每条记录之间使用,隔开

  •  Method 2, insert values ​​into all fields, format: insert into table name values(value 1, value 2, ...);
  • That is to say, by default, all fields are inserted sequentially, so we don't need to write the fields.
insert into student
values(1004, '李四他爸', 47),
(1005, '王五它妈', 40),
(1006, '胖子它老特', 20);
#可以向这样不指定任何字段,默认顺序插入所有字段

 Summary insert operation precautions:

  1. Values ​​and fields must correspond to the same number and type
  2. The data size of the value must be within the specified length of the field
  3. Except for integer\decimal types, values ​​of other field types must be enclosed in quotation marks (single quotation marks are recommended)
  4.  If you want to insert a null value, you can leave the field blank, or insert null

update table record

  • Syntax format: update table name set field 1=value, field 2=value... where condition;     
update student set name = '胖子他爹' where id = 1005;
# 跟新student表中id = 1005这条记录的name为胖子他爹

update student set name = '我是你爸', age = 100 where id = 1005;
# 跟新student表中id = 1005这条记录的name为我是你爸, age为100

 Summary and new record operation precautions:

  1. The type of the column name should be consistent with the modified value
  2. The value cannot exceed the length range of the field when modifying the value
  3. Except for integer\decimal types, the value of other field types must be enclosed in quotation marks

delete table record

  • Syntax format: delete from table name where condition;
delete from student where id = 1005;
# 从student 表中删除id=1005这条记录
delete from student where name = '胖子'
# 从student 表中删除name=胖子这条记录

It is still necessary to practice the operations of adding, deleting, modifying and checking records, because operations such as modifying, deleting, and adding specific records in the database are quite common.

2. Solve the problem of paging search left in the previous article

  •  What is the above? I believe that everyone who likes search records or shopping is not unfamiliar. This way of displaying records is to display records in pages (page search)
  • Paging query format: select * from table name limit startRow, pageSize;
#模拟这样一个场景, 每一页5条数据
select * from student limit 0, 5;  # 第一页
select * from student limit 5, 5;  # 第二页
select * from student limit 10, 5; # 第三页
  • Throwing a question, at this time we all know the number of data bars on each page, and the page size is fixed. The problem is that if we determine the startRow?
-- 后台计算出页码、页数(页大小)
-- 分页需要的相关数据结果分析如下,
-- 注意:下列是伪代码不用于执行
int curPage = 2; -- 当前页数
int pageSize = 5; -- 每页显示数量
int startRow = (curPage - 1) * pageSize; -- 当前页, 记录开始的位置(行数)计算
  • In fact, we just need to know the current number of pages (number of pages - 1) * pageSize; to know startRow

3. Detailed explanation of SQL constraints

  • Definition of Constraints

  • I actually need to learn about constraints. First, let’s figure out what constraints are. In fact, it’s quite simple. Constraints are a kind of restriction, so you can’t go beyond this control range.
  • The constraint in the database means that the data content in the table cannot be filled in randomly, and must be filled in according to the requirements. To ensure the integrity and security of the data

  • PRIMARY KEY constraint   

  • What is a primary key constraint: a unique constraint that is not null. The primary key constraint is not NULL, and uniquely identifies a record, almost every table must have such a constraint

Add primary key constraint

  • Method 1: When creating a table, in the field description, declare the specified field as the primary key:
  • Format: field name data type [length] primary key;
create table user_table(
	id int primary key, #添加主键约束
	name varchar(10),
	age tinyint
) engine = innodb charset = utf8mb4;
  • The primary key constraint uniquely identifies the record and cannot be empty
insert into user_table
values(1001, '翠花', 18);
#插入第一条记录翠花是没有问题的
insert into user_table
values(1001, '王五', 20);
#插入这条记录应当是报错, 重复插入主键了
# [Err] 1062 - Duplicate entry '1001' for key 'PRIMARY'
# 重复加入1001 作为主键

  • The primary key constraint cannot be null ( different from the unique primary key )
insert into user_table
values(null, '大胖', 30);
# 区别唯一约束, 主键约束不可以为null
#[Err] 1048 - Column 'id' cannot be null
  • Method 2: When creating a table, in the constraint area, declare the specified field as the primary key
  • Syntax form:     [constraint name] primary key (field list)
  • What is the necessity of appearing? The necessity of this method is to add a joint primary key. The use of the specific joint primary key is applied in the intermediate table below. Here we first learn how to create
create table persons (
	pid int,
	lastname varchar(255),
	firstname varchar(255),
	address varchar(255),
	constraint persons_pk primary key(lastname, firstname) 
	#通过constraint 增添联合主键
) engine = innodb default charset = utf8mb4;
  • Think about why the constraint of the joint primary key is needed. The primary key must be used to identify different records. Sometimes there is such a situation,     we need to use name + gender to identify different objects the same     (unfortunately, there are boys and girls named Wang Yujie In this case, only the name cannot be distinguished. In this case, the primary key can be combined with other fields to constrain the identification)
  • Method 3: After creating the table, declare the specified field as the primary key by modifying the table structure:
  • Format: altertable table name add [ constraint name ] primary key (field list)
alter table user_table 
add constraint name_id_pk primary key(name, id);
# 向user_table表中增加一个name + id的联合主键

remove primary key constraint

  • Format: alter table table name drop primary key;
alter table user_table drop primary key;
# 删除user_table表中的主键约束

Auto-increment column (introduces how primary key constraints can be separated from it)

  • We usually want the database to automatically generate the value of the field every time a new record is inserted
  • Especially the primary key field, if it is only used as a marked record, there is absolutely no need for us to set the value.
  • We can use the auto_increment (auto-increment column) keyword in the table, the type of the auto-increment column must be integer, and the auto-increment column must be the key (usually for the primary key)

Format: field name integer type [length] [constraint] auto_increment

create table test(
	id int primary key auto_increment,
	# 添加一个主键约束, 设置自动增长. 默认增长为1
	age tinyint,
	name varchar(20)
) engine = innodb default charset = utf8mb4;

insert into test values(null, 18, '小呼噜');
# 我们设置了主键自动递增可以不再需要传入主键字段
# 或者主键传入null 他会自动设置从1开始默认增量1

  • Or when insert into, it is OK not to pass in anything, and null can also be passed in

  • However, if we want to use the same as the above, we must pay attention to specifying the field to insert, otherwise the default is to give three values. When we specify the insert field, we don't need to specify the id, which    is a bit like the default value.
  • Not Null Constraint

  • NOT NULL constraint: The column does not accept NULL values. Fields are required to always contain a value. This means that you cannot insert new records or update records without adding a value to the field.

Add a not-null constraint

  • Format: field name data type [length] NOT NULL
drop table test;
create table test(
	id int primary key auto_increment,
	name varchar(10) not null,#设置非null 插入数据不能传入null
	age tinyint
) engine = innodb auto_increment = 10 default charset = utf8mb4;
# 我们还可以向这般指定auto_increment的值
insert test values(null, null, 28);
# 会出错, 第二个字段增加了not null 约束
# 传空会报错[Err] 1048 - Column 'name' cannot be null

remove not-null constraint   

  • Format: alter table table name modify field name data type [length]
alter table test modify name varchar(10);
# 非常简单的方式, 直接更改数据类型的不加null约束即可
desc test;

  • unique constraint

  • unique constraint: the value of the specified column cannot be repeated.

Notice: 

  1. Both UNIQUE and PRIMARY KEY constraints provide unique guarantees for columns. PRIMARY KEY is an automatically defined UNIQUE constraint.
  2.  Each table can have multiple UNIQUE constraints, but each table can have only one PRIMARY KEY constraint.
  3.  UNIQUE does not limit the number of occurrences of null values

add unique constraint

  • In the same way as the primary key is added, there are 3 types. I will give a few examples here
drop table test;
create table test (
	id int unique,	# 添加一个唯一约束
	name varchar(20) not null,
	age tinyint
) engine = innodb default charset = utf8mb4;
desc test;
insert into test values(null, '张三', 19);
# 允许传入null  区别primary key
insert into test 
values(1, '李四', 30),
(1, '王五', 38);  
#报错[Err] 1062 - Duplicate entry '1' for key 'id'

  • Format 2: [constraint name] UNIQUE (field) corresponds to primary key Mode 2
  • Format 3: ALTER TABLE table name ADD [CONSTRAINT name] UNIQUE (field) Comparison method 3

Delete the unique constraint in the same way as you just deleted the primary key constraint

  • default constraints

  • default constraint: used to specify the field default value. When inserting a record into the table, if the field is not explicitly assigned, the default value is automatically assigned
  • Add a default constraint and add the format when creating the table: field name data type [length] DEFAULT default value
CREATE TABLE persons (
 pid INT,
 lastname VARCHAR(255),
 firstname VARCHAR(255),
 address VARCHAR(255) DEFAULT '香港' -- 添加默认约束
)engine = innodb default charset = utf8mb4;
# 传入null 则会按照default 赋值
insert into persons(pid, lastname, firstname) 
values(2, '德华', '刘');
# 或者指定字段, default字段可以不用传入val

4. Multi-table operation

  • Originally, I planned to include the multi-table operation in one time, but I found that the multi-table operation seems to be more troublesome, and Xiaojie couldn't figure it out for a while, so Xiaojie will continue in the next chapter         (thanks to everyone for Xiaojie support ha)

5. Summary of this article

  • About the column operation of the table (add, delete, modify, check) at the beginning of the alter keyword, followed by add modify change drop

alter table table name add column name type (length) add a new column

alter table table name modify column name oldtype newtype only do type modification for a column

alter table table name change old column name new column name oldtype newtype can do type + list modification for a column

alter table table name drop column name; delete operation for a column

  • Recording operations on tables ( add, delete, modify, check )

insert into table name (specify field) values ​​(specify value), (specify value); specify insert field value (insert record)

insert into table name values ​​(all fields are written in order); insert field values ​​according to the order of the table fields

update table name set field = value where condition specified record change record

delete from table name where condition specified records delete records that meet the conditions from the specified table

  • Learning about various constraints

A constraint is a restriction

Primary key constraint (equivalent to a combination of unique constraint + non-null constraint), used to uniquely identify records in the table

The unique constraint is also kept non-repeatable, the column field value is unique, but null is allowed

Non-null constraint. That is, null is not allowed and null cannot be passed as a parameter

Default constraint, if null is passed in, the default field value is the initial default value

Friends, although the things introduced today are not difficult, we need to master the simple things in detail. If possible, we should try our best to test them. I wish you success in your studies, job promotion and salary increase.

Guess you like

Origin blog.csdn.net/weixin_53695360/article/details/123711464