MySQL基础讲义——约束与表管理

· 约束

约束作用:1.防止将错误值插入数据表;2.保持表中数据的一致性
包含哪些:1.非空约束、唯一约束、检查约束;2.主键约束、外键约束

图片名称
-- 主键约束   
create table s_user(   
u_id int auto_increment primary key,   
u_name varchar(20),   
u_pwd varchar(20)   
);    
# 添加自增列
create table s_user(
u_id int auto_increment primary key,
u_name varchar(20),
u_pwd varchar(20)
);
-- 外键约束   
-- 方法1   
create table s_order(   
o_id int auto_increment primary key,   
o_buyer_id int,   
o_totalprices float,   
foreign key(o_buyer_id) references s_user(u_id)   
);   
-- 方法2   
create table s_order2(   
o_id int auto_increment primary key,   
o_buyer_id int,   
o_totalprices float    
);  
alter table s_order2 add foreign key(o_buyer_id)   references s_user(u_id);   

· 表管理

-- 添加数据   
insert into s_user(u_name,u_pwd) values("carry","123");   
insert into s_user(u_name,u_pwd) values("carry","123"),("harry","456"),("marry","789");   
-- 修改数据   
set sql_safe_updates=0; #设置数据库安全等级  
update s_user set u_pwd="963" where u_name="harry";   
-- 删除数据   
delete from s_user where u_name="marry";

· 单元测试

创建员工表emp

图片名称

· 相关连接

MySQL基础讲义—— 数据库与表空间
MySQL基础讲义—— 约束与表管理
MySQL基础讲义—— SQL查询

分类: 数据库技术