Day27 MySql对表操作的一些命令

1.外键的增删

--外键:给数据加一定的限制条件
--一般来说,定义的数据范围来自一个表的一个字段(唯一且非空):来源
--要用到这些数据的表,要和该表建立外键约束,那么使用的数据不能超出来源的范围
建表时增:
constraint 外键名 foreign key(本表字段) references 来源表(来源字段)
已有表后增:
alter table 表名 constraint 外键名 foreign key (本表字段) refereces 来源表(来源字段);
删外键:
alter table 表名 drop foreign key 外键名;
alter table subject drop foreign key sub_g_key;
--删除subject表中sub_g_key键外键
外键的作用:以一个来源限制数据的范围(字典表)
create table student(
    stuId int(11) auto_increment primary key,
    stuName varchar(50),
    gradeId int(4),
    phone varchar(15),
    address varchar(2000),
    birthday date,
    constraint `s_g_key` foreign key(gradeId) references grade(GradeId)
);
--建student表并添加外键
alter table subject add constraint sub_g_key foreign key foreign key (gradeId)
refereces grade(GradeId);
--在表中添加外键属性
---------------------------------------
insert into student values
--在student表中插入多行数据
(2,'旭东',1,18550557900,'警官学院',now()),
(3,'陈建',2,18550447900,'警官学院',now()),
(4,'黎明',1,18550552300,'警官中学',now()),
(5,'名流',1,18553457900,'警官小学',now()),
(6,'康康',1,18554557900,'警官中专',now());
INSERT INTO grade VALUES (1,'大一'),(2,'大二'),(3,'大三'),(4,'大四');
--在grade表中插入多行数据
insert into student (gradeId,birthday,address,stuName)values
--student表中插入多行数据
(1,now(),'警官大学','葛java'),
(2,now(),'警官大学','一凡'),
(3,now(),'警官大学','郭楠'),
(4,now(),'警官大学','华子');
备注:插入的顺序要和上面一一对应
----------------------------------------------
alter table subject modify  SubjectNo int(11) auto_increment primary key;
--修改subject表中SubjectNo列将其设为自增并将其添加为主键
--auto increment为自增的意思,自增的意思是为了确保它是一定不重复的

2.表中添加列

insert into subject(SubjectNo,.......)
--在subject表中插入多个列

3.修改表中的内容:

update subject set SubjectName='高等数学' where SubjectNo=1;
--将subject表中的SubjectName列中SubjectNo为1的行的值改为‘高等数学’、
update subject set SubjectName='mysql', ClassHour=150,where SubjectNo=1;
--将subject表中的第一行SubjectName的值改为mysql,ClassHour的值改为150
update subject set GradeId=3 where ClassHour between 110 and 130;
--将ClassHour中110-130之间的GradeId的值都改为3(这种效率更高)
update subject set GradeId=3 where ClassHour >= 110 and ClassHour <= 130;
--将ClassHour中110-130之间的GradeId的值都改为3(这种会执行查找两次)
备注:and相当于&&,可以这么写,但不建议
update subject set GradeId=3 where ClassHour >= 110 or ClassHour <= 130;
备注:使用or会大大降低效率,实际中尽量避免用or

4.查看表里的详细内容

select * from

select *from user where username='root' and password='123';
--查询用户名为root,密码为123的用户
select *from user where username='root' and password='123' or 1=1;
--sql注入,不管输入啥,都会成功,因为1永远等于1
备注:between只能和and连用,不能和or
对null的判断是is和not,不能用=和!=。

5.delete命令:

delete from student where is null;
--删除student表中phone列中null的行删除
truncate table student;
--都是删除表
--重置表的状态,无法恢复,相当于初始化,会重新设置auto_increment。区别delete,delete是可以恢复的,
--delete是不可自增的。
*.frm表结构定义文件
alter table student modify  Sex int(2) auto_increment primary key;

6DML语句总结:

insert into 表名 [(字段列表)] values (值的列表)[,...];
update 表名 set 字段名=值[,...][where 条件语句];
delete from 表名 where 条件语句;
truncate table 表名;

猜你喜欢

转载自blog.csdn.net/yuanlaishidahuaa/article/details/121503123