使用DML插入、删除、更新数据

一、使用DML插入数据

1.往学院表添加新的数据

a.单独写入

insert into tb_college (col_id, col_name, col_tel) values (default, '计算机学院',  '028-44556677');
insert into tb_college (col_name, col_tel) values ('外国语学院', '028-55667788');
insert into tb_college values (999, '文学院', '028-77889900');
insert into tb_college values (default, '理学院', '028-89898989');

b.批处理insert

insert into tb_college (col_name, col_tel)
values
    ('计算机学院', '028-44556677'),
        ('外国语学院', '028-55667788'),
        ('文学院', default);

2.往学生表添加新的数据

a.单独写入

insert into tb_student (stu_id, stu_name, stu_sex, stu_birth, col_id) values ('1001', '王大锤', '男', '1995-5-5', '101');

b.批处理

insert into tb_student (stu_id, stu_name, stu_sex, stu_birth, col_id)
values
    (1002, '李元芳', '男', '1998-12-1', '102'),
    (1003, '武则天', '女', '1995-12-1', '102');

二、使用DML删除和更新数据

1.更新学生表数据

a.单行写入

delete from tb_student where stu_id = 1004;

b.批处理

delete from tb_student where stu_id = 1002 or stu_id = 1003;
delete from tb_student where stu_id in (1002, 1003);

2.查看系统安全变量

show variables like '%safe%'

有子表参照的父表不能被删除

3.及连删除,当删除学院的时候同时删除该学院的学生

alter table tb_student drop constraint fk_student_cid;

-- on delete restrict / cascade / set null
alter table tb_student add constraint fk_student_cid 
foreign key (col_id) references tb_college (col_id)
on delete cascade;

注意:这里的外键名字不能跟之前的外键名字重复,但是我已经将之前的外键已经删除了,很奇怪。
delete后面写restrict,意为不让删;写set null,意为父表删了之后子表对应外键的值设置为空,并且要允许为空才行。

4.更新学院表数据

update tb_college set col_name = '计算机学院', col_tel = '028-12345678' where col_id = 102;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老树盘根_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值