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的對于自增長欄位的影響:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/553473.html
標籤:MySQL
下一篇:返回列表
