每一张表通常会有一个且只有一个主键,来表示每条数据的唯一性。
特性:值不能重复,不能为空 null
格式:create table test (ID int primary key)
主键 + 自增的写法:
格式:create table test (ID int primary key auto_increment)
注意:自增只能配合主键来使用(如果单独定义则会报错)
mysql> alter table test modify Name varchar(12) comment '用户名';
mysql> create table A(ID int primary key auto_increment,Name varchar(12),Department int); mysql> create table B(ID int primary key auto_increment,Name varchar(12)); mysql> insert into B(Name) values("财务"),("市场"); mysql> insert into A(Name,Department) values("张三",1),("李四",2),("王五",2);
mysql> select B.Name 部门,A.Name from B,A where B.ID=2 and A.Department=2;
数据库:关系型数据库(支持事务);非关系型数据库(不支持)
一个事务中包含多条 SQL 语句,而且这些 SQL 语句之间存在一定的关系:
事务特性 | 作用 |
---|---|
原子性(Atomic) | 事务的所有操作,要么全部完成,要么全部不完成,不会结束在某个中间环节。 |
一致性(Consistency) | 事务开始之前和事务结束之后,数据库的完整性限制未被破坏。 |
隔离性(Isolation) | 当多个事务并发访问数据库中的同一数据时,所表现出来的是相互关系。 |
持久性(Durability) | 事务完成之后,所做的修改会进行持久化保存,不会丢失。 |
区别:
隔离级别:
隔离级别 | 作用 |
---|---|
SERIALIZABLE (串行化) |
避免脏读、不可重复读、幻读 |
REPEATABLE-READ (可重复读) |
避免脏读、不可重复读 |
READ-COMMITTED (读已提交) |
避免脏读 |
READ-UNCOMMITTED (读未提交) |
无作用 |
MySQL 支持上面 4 种隔离级别,默认为可重复读。如若想修改隔离级别需: sed -i '/\[mysqld]/a transaction-isolation = SERIALIZABLE' /etc/my.cnf
mysql> show variables like '%tx_is%'; mysql> exit [root@MySQL ~]# sed -i '/\[mysqld]/a transaction-isolation = SERIALIZABLE' /etc/my.cnf [root@MySQL ~]# systemctl restart mysqld [root@MySQL ~]# mysql -uroot -p123123 -e "show variables like '%tx_is%';"
管理事务的三个命令:
mysql> create table C(ID int); mysql> insert into C values(1),(2); mysql> select * from C; mysql> BEGIN; mysql> insert into C values(3); mysql> COMMIT; mysql> select * from C;
mysql> show variables like 'autocommit'; #查看是否开启自动提交事务 mysql> BEGIN; mysql> insert into C values(4) mysql> select * from C; mysql> exit [root@localhost ~]# mysql -uroot -p123123 -e "select * from Coco.C where ID=4"
set autocommit=0
:在数据库中修改为临时生效(如若想永久修改需 sed -i '/\[mysqld]/a autocommit=0' /etc/my.cnf
来修改)
mysql> set autocommit=0; mysql> select * from Coco.C; mysql> insert into Coco.C values(4); mysql> select * from Coco.C where ID=4; [root@localhost ~]# mysql -uroot -p123123 -e "select * from Coco.C where ID=4"
注意:
mysql> select ID as "编号",Name as "姓名",Department as "部门" from A where ID=1; mysql> select ID "编号",Name "姓名",Department "部门" from A where ID=1;
mysql> select distinct Department from A;
AND:逻辑与(条件都要满足);OR:逻辑或(条件只需要满足一个)。
mysql> select * from A where ID >= 3 and Department = 2; mysql> select * from A where ID >= 3 or Department = 2;
mysql> select * from A where ID in(1,3,4); mysql> select * from A where ID not in(1,3,4); mysql> select * from A where ID between 1 and 3;
mysql> select * from A where Name like "%三%"; mysql> select * from A where Name like "%三%" or Name like "%四";
mysql> select * from A order by ID desc; mysql> select * from A order by Department,ID desc;
mysql> select * from C; mysql> select * from C limit 2; mysql> select * from C limit 0,2;
到此这篇关于MySQL主键与事务的文章就介绍到这了,更多相关MySQL主键与事务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!