Home > Database > Mysql Tutorial > body text

MySQL's DML advanced, paging search, SQL constraints and multi-table operation methods

WBOY
Release: 2023-05-31 19:10:34
forward
911 people have browsed it

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

1. What is DML, and basic DML operations, table column and row update operations

  • Modify the column

#首先简单的创建一个student表为后序操作做准备
use test;
create table student (
	id int,
	name varchar(8),
	age tinyint
) engine = innodb default charset = utf8mb4;
desc student;
Copy after login
  • MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • ##Add new Column, format: alter table table name add new column name data type (length);

  • alter table student add addr varchar(20);
    #新增一个addr列出来
    Copy after login
  • Modify column data type ( length), 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))
    Copy after login
  • 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不可以修改列名
    Copy after login
  • ##. Delete Specify the column, format: alter table table name drop column name;

    alter table student drop stu_addr;
    # 删除student表中的stu_addr列
    Copy after login
  • For the above modification operation of the column structure of the table It is not recommended to use it, 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 done well, data loss will be bad,

    Various operations on table rows and table records (add, delete, modify, query)
Insert table records

  • Method 1, insert the specified field, format: insert into table name (field 1, field 2, ...) values ​​(value 1, value 2, ...) I call this method called the insert operation of the specified field.

    # 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, and there is no need to write the fields MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • insert into student(id, name, age) values(1000, '张三', 18);
    # 向student表中插入一条id 为1000 name 为张三, age 18的记录
    Copy after login

  • Summary Notes on insertion operations:
  • Values ​​and fields must correspond, with the same number and the same type

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

Value data The size must be within the specified length range of the field

  1. Except for integer\decimal types, values ​​of other field types must be enclosed in quotes (single quotes are recommended)

  2. If you want to insert a null value, you can leave the field blank or insert null

  3. Update table record

  4. Syntax format: update table name set field 1=value, field 2=value... where condition;

insert into student(id, name, age)
values(1001, '李四', 20),
(1002, '王五', 22),
(1003, '胖子', 25);
#还可以支持values后面跟上多条记录
#每条记录之间使用,隔开
Copy after login

insert into student
values(1004, '李四他爸', 47),
(1005, '王五它妈', 40),
(1006, '胖子它老特', 20);
#可以向这样不指定任何字段,默认顺序插入所有字段
Copy after login

    Summary and notes on new record operations:
  • Column The type of the name must be consistent with the modified value

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

When modifying the value, it cannot exceed the length range of the field

  1. Except for integer\decimal types, values ​​of other field types must be enclosed in quotation marks

  2. Delete table records

  3. Syntax format: delete from table name where condition;

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

What needs to be practiced well is the operation of adding, deleting, modifying and checking records , because operations such as modification, deletion, and addition of specific records in the database are very common

  • Solve the problem of paging search

##What is this thing above? I believe that everyone who likes to search records or shop is familiar with it. This way of displaying records is to display records in pages (search in pages)

The format for paging queries is: SELECT * FROM table_name LIMIT start_row, page_size;

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

    delete from student where id = 1005;
    # 从student 表中删除id=1005这条记录
    Copy after login
  • Throwing a question, at this time we all know the number of data items on each page, and the page size is fixed. The question is if we determine startRow based on the number of pages we need to query?

-- 后台计算出页码、页数(页大小)
-- 分页需要的相关数据结果分析如下,
-- 注意:下列是伪代码不用于执行
int curPage = 2; -- 当前页数
int pageSize = 5; -- 每页显示数量
int startRow = (curPage - 1) * pageSize; -- 当前页, 记录开始的位置(行数)计算
Copy after login
  • 其实我们仅仅只是需要知道当前页数 (页数 - 1) * pageSize; 即可获知startRow

三. SQL约束详解

  • 约束的定义

  • 竟然需要学一下约束,首先我们先搞定啥叫约束,其实还蛮简单的,约束就是⼀种限制条件, 让你不能超出这个控制范围

  • 而在数据库中的约束, 就是指 表中的数据内容 不能胡乱填写, 必须按照要求填写. 好保证数据的完整性与 安全性

  • 主键约束 PRIMARY KEY 约束

  • 啥是主键约束:不为空的唯一约束. 主键约束不为NULL, 且唯一标识一条记录, 每一个表几乎都必须存在这样一个约束条件

添加主键约束

  • 方式1:创建表时,在字段描述处,声明指定字段为主键:

  • 格式: 字段名 数据类型[长度] primary key;

create table user_table(
	id int primary key, #添加主键约束
	name varchar(10),
	age tinyint
) engine = innodb charset = utf8mb4;
Copy after login
  • 主键约束唯一标识记录, 且不可以为空

insert into user_table
values(1001, '翠花', 18);
#插入第一条记录翠花是没有问题的
insert into user_table
values(1001, '王五', 20);
#插入这条记录应当是报错, 重复插入主键了
# [Err] 1062 - Duplicate entry '1001' for key 'PRIMARY'
# 重复加入1001 作为主键
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • 主键约束不可以为空 (区别unique 主键)

insert into user_table
values(null, '大胖', 30);
# 区别唯一约束, 主键约束不可以为null
#[Err] 1048 - Column 'id' cannot be null
Copy after login
  • 方式2:创建表时,在constraint约束区域,声明指定字段为主键

  • 语法形式: [constraint 名称] primary key (字段列表)

  • 出现的必要是什么? 这种方式出现的必要就是可以添加联合主键, 具体联合主键的使用回在下文中的中间表处应用, 此处我们先获悉如何创建

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;
Copy after login
  • 思索一下为何需要出现联合主键这一约束, 主键必须是标识不同的记录, 有些时候存在这样一种情况, 我们需要用 姓名 + 性别, 来辨识不同的对象一样 (不巧存在男生女生都叫王玉杰的情况, 仅姓名无法区分, 此时可以联合其他字段共同构成主键来约束标识)

  • 方式三:创建表之后,通过修改表结构,声明指定字段为主键:

  • 格式: altertable 表名 add [ constraint 名称] primary key (字段列表)

alter table user_table 
add constraint name_id_pk primary key(name, id);
# 向user_table表中增加一个name + id的联合主键
Copy after login

删除主键约束

  • 格式: alter table 表名 drop primary key;

alter table user_table drop primary key;
# 删除user_table表中的主键约束
Copy after login

自动增长列 (介绍主键约束如何离得开它)

  • 我们通常希望在每次插⼊新记录时,数据库自动生成字段的值

  • 又特别是主键字段, 如果仅作为标记记录,完全没必要我们设置值呀

  • 我们可以在表中使用 auto_increment(自动增长列)关键字,自动增长列类型必须是整形,自动增长 列必须为键(通常是用于主键)

格式: 字段名 整数类型[长度][约束] auto_increment

create table test(
	id int primary key auto_increment,
	# 添加一个主键约束, 设置自动增长. 默认增长为1
	age tinyint,
	name varchar(20)
) engine = innodb default charset = utf8mb4;
Copy after login
insert into test values(null, 18, '小呼噜');
# 我们设置了主键自动递增可以不再需要传入主键字段
# 或者主键传入null 他会自动设置从1开始默认增量1
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • 亦或是 insert into 的时候不传入任何东西都OK, null也可以不用传入

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • 不过如果想要同上述这般使用我们必须注意的就是要指定字段插入, 不然默认是三个都要给值, 我们指定插入字段的时候可以无需指定id, 有点像默认值

  • 非空约束

  • NOT NULL 约束: 列不接受 NULL 值。 要求字段始终包含值。如果没有向字段添加值,则无法插入新记录或更新记录

添加非空约束

  • 格式: 字段名 数据类型[长度] 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的值
Copy after login
insert test values(null, null, 28);
# 会出错, 第二个字段增加了not null 约束
# 传空会报错[Err] 1048 - Column 'name' cannot be null
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

删除非空约束

  • 格式: alter table 表名 modify 字段名 数据类型[长度]

alter table test modify name varchar(10);
# 非常简单的方式, 直接更改数据类型的不加null约束即可
desc test;
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • 唯一约束

  • unique 约束: 指定列的值 不能重复.

注意:

  1. 唯一性约束和主键约束都为列提供了独一无二的保证。PRIMARY KEY 是自动定义的 UNIQUE 约束。

  2. 每个表可以有多个 UNIQUE 约束,但是每个表只能有⼀个 PRIMARY KEY 约束。

  3. UNIQUE 不限制 null 值 出现的次数

添加唯⼀约束

  • 与主键添加方式相同,共有3种. 我在此处举几个例子就是

drop table test;
create table test (
	id int unique,	# 添加一个唯一约束
	name varchar(20) not null,
	age tinyint
) engine = innodb default charset = utf8mb4;
desc test;
Copy after login
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'
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

  • 格式2: [constraint 名称] UNIQUE (字段) 对应primary key 方式2

  • 格式3: ALTER TABLE 表名 ADD [CONSTRAINT 名称] UNIQUE (字段) 对比方式3

删除唯一约束, 方式一样跟刚刚删除主键约束

  • 默认约束

  • default 约束: 用于指定字段默认值。如果插入记录时某些字段没有赋值,则会自动填充默认值

  • 添加默认约束,在创建表时候添加 格式: 字段名 数据类型[长度] DEFAULT 默认值

CREATE TABLE persons (
 pid INT,
 lastname VARCHAR(255),
 firstname VARCHAR(255),
 address VARCHAR(255) DEFAULT '香港' -- 添加默认约束
)engine = innodb default charset = utf8mb4;
Copy after login
# 传入null 则会按照default 赋值
insert into persons(pid, lastname, firstname) 
values(2, '德华', '刘');
# 或者指定字段, default字段可以不用传入val
Copy after login

MySQLs DML advanced, paging search, SQL constraints and multi-table operation methods

小结

  • 关于表的列操作  (增删改查)  开头alter 关键字  后面add modify change drop

alter table 表名 add 列名 类型(长度)   新增一列

alter table 表名 modify 列名  oldtype   newtype  针对一列仅仅只做类型修改

alter table 表名 change  old列名  new列名  oldtype   newtype 针对一列可做类型 + 列明修改

alter table 表名 drop 列名;  针对一列做删除操作

  • 关于表的记录操作 (增删改查)

insert into 表名(指定字段) values(指定值), (指定值);    指定插入字段值  (插入记录)

insert into 表名  values(所有字段顺序写入值);              按照建表字段顺序插入字段值

update 表名 set 字段 = 值 where 条件指定记录             更改记录

delete from 表名 where 条件指定记录                            从指定表中删除满足条件的记录

  • 关于各种约束的学习

约束就是一种限制

主键约束  (相当于是 unique 约束 + 非 null约束的结合), 用来唯一标识表中的记录

unique 约束, 也是保持不可重复, 列字段值唯一, 但是允许为null

非 null 约束. 就是不允许为null 不可以传入null作为参数

默认约束, 如果传入null 就默认字段值为初始默认值

The above is the detailed content of MySQL's DML advanced, paging search, SQL constraints and multi-table operation methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!