数据操作
1.添加记录
不列出属性字段
insert user values(default,'lili',25,'lili@qq.com');
列出属性字段
insert user(username,email) values('rose','rose@qq.com');
一次性插入多条数据,可以列出属性字段名 也可以不列出属性字段名
-- 列出属性字段名
insert user(username,email) values
('jack','jack@qq.com'),
('hero','hore@qq.com'),
('gary','gary@qq.com');
-- 不列出属性字段名
insert user values
(default,'balin',22,'jack@qq.com'),
(default,'yoeker',24,'hore@qq.com'),
(default,'sunli',25,'gary@qq.com');
使用set插入数据
insert user set username='cserler',age=18,email='csecicici@qq.com';
从其他表中导入数据
-- 把user_test表中的nickname所有数据导入到user表中的username字段下
insert user(usernmae) select nickname from user_test;
2.修改记录
-- 把user表中id等于1的数据的age字段值改为20
update user set age=20 where id=1;
-- 把user表中id等于1的数据的age字段值改为22 username改为hope
update user set age=22,username='hope' where id=1;
-- 把user表中的所有数据age加10
update user set age=age+10;
-- 把user 表中所有的的email字段设置为默认值
update user set email=default;
3.删除记录
-- 删除user表中username为king的记录
delete from user where username='king';
-- 删除user表中age=28的记录
delete from user where age=28;
-- 删除表中所有记录 此操作只是清空数据 并不重置自动增长的序号
delete from user;
4.其他操作
外键 foreign key(${本表字段}) references ${主表}(${主表主键})
子表外键必须关联主表的主键
子表的外键字段跟主表的主键字段要类似,类型一致,无符号一致,长度可以不同
-- 把本表的cateId作为外键 引用到news_cate表中的id字段,news表作为子表,news_cate作为主表
create table if not exists news(
id int unsigned not null auto_increment key comment '编号',
title varchar(100) not null unique comment '新闻标题',
content varchar(1000) not null comment '新闻内容',
cateId tinyint unsigned not null comment '新闻所属分类编号',
[constraint cateId_fk_newsCate] foreign key(cateId) references news_cate(id)
)engine=innodb;
动态添加外键与添加外键
-- 删除外键
alter table news
drop foreign key cateId_fk_newsCate;
判断字段为空
...username is null;
...username<=>null;
重置自动增长序号,必须要数据表没有数据此操作才有效。
alter table user auto_increment=1;
出厂化数据表
-- 把user表所有数据进行清空 并且自动增长序号重置为1
truncate user;