一、数据库的基础使用:
创建数据库:
create database 数据库名
命名规则: 数据库名不能重名
查看已创建好的数据库:
show databases;
删除数据库:
drop database 数据库名;
使用数据库:
use 数据库名;
创建表:
create table 表名 (
属性名1 数据类型
…
属性名N 数据类型 完整性约束
);
修改表:
添加字段: alter table 表名 add 字段名 字段类型 约束
修改字段类型: alter table 表名 modify 属性名 字段类型
修改字段名和字段类型: alter table 表名 change 原字段名 新字段名 字段类型 约束
删除字段: alter table 表名 drop 字段名;
删除表:
drop table 表名;
插入语句:
属性不可缺省方式:
insert into(into可以不写) 表名 values(属性值…)
属性可缺省方式:
insert into(into可以不写) 表名 (属性1,属性2,属性3,属性4…)
values(属性值1,属性值2,属性值3,属性值4…);
删除语句:
delete from 表名 where 筛选条件;
例如:
删除年纪大于60岁的人
delete from student where age > 60;
修改语句:
update 表名 set 属性1 = 新值1,属性2 = 新值2 … where 筛选条件;
例如:update student set name = ‘小飞’ where id = 5;
子查询:
是将一个查询语句嵌套到另一个查询语句中。内层查询的结果可以为外层查询提供查询条件
子查询的语法:
select 属性列表 from 表1 where 连接方式 (select 属性列表 from 表2 where 刷选条件);
where之后+ 筛选条件/查询条件
内层查询
外层查询
目的:某一张表中的一部分数据,作为另一个表中的查询条件。
连接方式:in 、not in、exists not exists、 比较运算符、 比较运算符和any/all的结合
1:exists
当内层查询查询到结果是记为true 这是外层查询才执行,否则外层查询不执行。
if(内层查询查询到结果){ //内层查询查询到结果 为true
外层查询开始执行
}
2:not exists
if(!内层查询查询到结果){ //内层查询查询到结果 为true
内层查询开始执行
}
3:比较运算符:
select * from A where id = (select id from B where id > 70); 报错。
select * from A where id = (89 78 90 109 108); 报错
< > <= >= !=
所有的比较运算符 只能和一个数字进行比较,如果内层查询返回多个数据,请用in 和 not in 进行比较。
联合查询:
内连接:
能够把多挣表中意义相同字段相等时的那部分数据查出来。
语法:
(1)select 表1.属性名,… 表3.* from 表1,表2,表3…
where 表1.EX = 表2.EX and 表2.EX = 表3.EX and 表3.EX =表4.EX …;
外连接:
– 左连接查询
select 表1.属性名,… 表3.* from 表1 left join 表2 on 表1.EX = 表2.EX left join 表3 on
表2.EX = 表3.EX …;
– 右连接查询
select 表1.属性名,… 表3.* from 表1 right join 表2 on 表1.EX = 表2.EX right join 表3 on
表2.EX = 表3.EX …;
外键:多张表之间的约束
父表 子表:外键建在哪个表中哪个表就成为子表 references 后面跟的是父表。
插入数据的限制: 对父表没有限制,子表中的数据必须和父表一致。
注意:先创建父表再创建子表。
例如:
create table class_table(
class_id int primary key,
class_name varchar(8)
);
create table student_table(
stu_id int primary key auto_increment,
class_id int,
name nvarchar(10) unique,
age int default 0,
sex enum(‘m’,‘w’) not null,
foreign key(class_id) references class_table(class_id)
);
class_table 是 student_table 的父表。
设置表的字符编码:有时候MySQL中的表需要存储中文,需要设置表的字符编码为utf8。
例如:
CREATE TABLEstudent_tb2
(Sname
varchar(10) CHARACTER SET utf8
);
例如:
CREATE TABLE stu_test
(
name` varchar(10) DEFAULT NULL,
) CHARSET=utf8;
来源:CSDN
作者:l呃呃
链接:https://blog.csdn.net/weixin_44456243/article/details/104619126