DML操作: Data Manipulation Language,數據操縱語言;包含insert、update、delete操作; 1、單行插入數據格式: insert into 表名【欄位列表】 values(值列表); 向教師表插入: insert into teacher values('0 ...
DML操作:
Data Manipulation Language,數據操縱語言;包含insert、update、delete操作;
1、單行插入數據格式:
insert into 表名【欄位列表】 values(值列表);
向教師表插入:
insert into teacher values('001','李老師', '1110000000'); insert into teacher(teacher_no, teacher_name,teacher_contact) values('002','王老師','1110000001'); insert into teacher(teacher_name,teahcer_no,teacher_contact) values('孫老師','003','1110000002');
向班級表插入:
insert into classes values(null,'2023自動化1班','自動化'); insert into classes(class_name,department_name) values('2023自動化2班','自動化'); insert into classes values(3,'2023自動化3班','自動化');
向課程表插入:
insert into course values(null,'c語言',default,'暫無','已審核','001'); 或者 insert into course (course_name,description,status,teacher_no) values('c語言','暫無','已審核','001'); insert into course values(null,'MySQL',150,'暫無','已審核','002'); insert into course values(nuil,'c++',230,'暫無','已審核','003');
2、批量插入多行數據格式:
insert into 表名【欄位列表】 values(值列表1),(值列表2),..(值列表n);
向學生表批量插入:
insert into student values('2023001','張三','2220000000',1),('2023002','李四','2220000001',1),('2023003','王五','2220000002',3),('2023004','馬六','2220000003',2),('2023005','田七','2220000004',2);
3、查詢插入多行數據:
insert into 目標表名【欄位列表1】 select(欄位列表2) from 源表 where 條件表達式;
先創建一個新表:
create table stu1 like student; insert into stu1 select * from student; select * from stu1;
4、update語句:
update 表名 set 欄位名1=值1[,欄位名2=值2] [where 條件表達式];
新建一個表,做測試:
create table exam ( stu_no int auto_increment primary key, exam_score tinyint unsigned, regular_score tinyint unsigned ); insert into exam values(null,80,85),(null,99,90),(null,65,70),(null,52,null),(null,20,null);
update exam set exam_score=exam_score+5; update exam set exam_score=100 where exam_score>=100; update exam set exam_score=60 where exam_score>=55 and exam_score<60;
update之後,要滿足鍵值約束;
5、刪除表數據:
delete from 表名 [where 條件表達式];
條件刪除:
delete from exam where exam_score<=50;
清空表:
刪除也要滿足約束限制;
總結:
對於主表:刪除、更新數據可能會違反外鍵約束,添加數據不會違反外鍵約束;
對於從表:刪除數據不會違反外鍵約束,添加和更新可能會違反外鍵約束;
6、truncate語句:
截斷表,相當於沒有where字句的delete語句;但是不能用於主表,即使沒有子表,也不能刪除;
格式:
truncate table table_name;
測試:
truncate table student; insert into exam values(null,80,80); truncate table exam; insert into exam values(null,80,80);
對於自增長欄位,truncate之後,編號重新從1開始;但是delete數據,編號仍然繼續增加;
使用truncate的對於自增長欄位的影響: