1准备
1.1准备测试数据
- 将sql文件导入到mysql中
- source soctt_data.sql
2交叉连接(笛卡尔积)
- select e.*, k.* from employee e cross join lvke k;
3自连接(等值连接)
- select e.,c. from employee e inner join class c on e.id=c.id;
- 其中的inner可省略
3.1总结:与oracle的不同
逗号–改变为–>inner join
where–改变为–>on
4外连接
4.1左外连接
select e.,c. from employee e left outer join class c on e.id=c.id;
4.2右外连接
select e.,c. from employee e right outer join class c on e.id=c.id;
- 总结:
- 外连接取值是与关系表达式=左右的位置无关,取值跟from后表的书写顺序有关
- xx left outer join yyy则为取出xxx内容
- xxx left outer join yyy则为取出yyy内容
5 小结
- 因为mysql 不支持使用nvl
- 所以使用 ifnull
- ifnull(e.name,‘his wife’)
6表的约束
6.1概念
- 定义主键约束:不允许为空,不允许重复:primary key
- 定义主键自动增长:auto_increment
- 定义唯一约束:unique
- 定义非空约束: not null
- 定义外键约束 :constraint ordersid_FK foreign key(ordersid) references orders(id)
- 删除主键: alter table tablename drop primary key;
测试准备
create table class1(
id int PRIMARY key auto_increment,
name VARCHAR(20) UNIQUE
);
create table student (
id int PRIMARY key auto_increment,
name VARCHAR(20) UNIQUE,
password VARCHAR(15) not null,
class1id int,
constraint stu_class1id_FK foreign key(class1id) references class1(id)
);
6.3测试
- 主键自增长
insert into class1(name) values('音乐');
insert into class1(name) values('体育');
- 赋值主键
insert into class1(id,name) values(5,'美术');
insert into class1(name) values('社会');
- 注意:要插入的是部分列 一定要在class表名后面写上列名 表示要插入那些列 由于class id为主键 所以不用显示插入 mysql会自动插入 而且会自动增长 保证不重复。
- insert into student(id,name,password,class1id) values(null,'小红','12345',1);
-
总结 若给主键插入一个null ,mysql会自动插入一个有效值 所以mysql主键肯定不为空
-
测试主键的唯一性、
- insert into student(id,name,password,class1id) values(1,'小化','12345',1);
- 1062 - Duplicate entry '1' for key 'PRIMARY'
- 测试name唯一性
- insert into student(name,password,class1id) values('小化','12345',1);
- 1062 - Duplicate entry '小化' for key 'name'
- 测试password非空性
- insert into student(name,password,class1id) values('小路',null,1);
- 1048 - Column 'password' cannot be null
- 测试classid外键约束
- insert into student(name,password,class1id) values('小往','12345',10);
- > 1452 - Cannot add or update a child row: a foreign key constraint fails (`lvke`.`student`, CONSTRAINT `stu_class1id_FK` FOREIGN KEY (`class1id`) REFERENCES `class1` (`id`))