數(shù)據(jù)操作
1.添加記錄
不列出屬性字段
insert user values(default,'lili',25,'lili@qq.com');
列出屬性字段
insert user(username,email) values('rose','rose@qq.com');
一次性插入多條數(shù)據(jù),可以列出屬性字段名 也可以不列出屬性字段名
-- 列出屬性字段名
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插入數(shù)據(jù)
insert user set username='cserler',age=18,email='csecicici@qq.com';
從其他表中導(dǎo)入數(shù)據(jù)
-- 把user_test表中的nickname所有數(shù)據(jù)導(dǎo)入到user表中的username字段下
insert user(usernmae) select nickname from user_test;
2.修改記錄
-- 把user表中id等于1的數(shù)據(jù)的age字段值改為20
update user set age=20 where id=1;
-- 把user表中id等于1的數(shù)據(jù)的age字段值改為22 username改為hope
update user set age=22,username='hope' where id=1;
-- 把user表中的所有數(shù)據(jù)age加10
update user set age=age+10;
-- 把user 表中所有的的email字段設(shè)置為默認(rèn)值
update user set email=default;
3.刪除記錄
-- 刪除user表中username為king的記錄
delete from user where username='king';
-- 刪除user表中age=28的記錄
delete from user where age=28;
-- 刪除表中所有記錄 此操作只是清空數(shù)據(jù) 并不重置自動(dòng)增長(zhǎng)的序號(hào)
delete from user;
4.其他操作
外鍵 foreign key(${本表字段}) references ${主表}(${主表主鍵})
子表外鍵必須關(guān)聯(lián)主表的主鍵
子表的外鍵字段跟主表的主鍵字段要類似氛悬,類型一致则剃,無(wú)符號(hào)一致,長(zhǎng)度可以不同
-- 把本表的cateId作為外鍵 引用到news_cate表中的id字段如捅,news表作為子表棍现,news_cate作為主表
create table if not exists news(
id int unsigned not null auto_increment key comment '編號(hào)',
title varchar(100) not null unique comment '新聞標(biāo)題',
content varchar(1000) not null comment '新聞內(nèi)容',
cateId tinyint unsigned not null comment '新聞所屬分類編號(hào)',
[constraint cateId_fk_newsCate] foreign key(cateId) references news_cate(id)
)engine=innodb;
動(dòng)態(tài)添加外鍵與添加外鍵
-- 刪除外鍵
alter table news
drop foreign key cateId_fk_newsCate;
判斷字段為空
...username is null;
...username<=>null;
重置自動(dòng)增長(zhǎng)序號(hào),必須要數(shù)據(jù)表沒(méi)有數(shù)據(jù)此操作才有效伪朽。
alter table user auto_increment=1;
出廠化數(shù)據(jù)表
-- 把user表所有數(shù)據(jù)進(jìn)行清空 并且自動(dòng)增長(zhǎng)序號(hào)重置為1
truncate user;