一、连接查询
1.交叉连接
select * from 表1 cross join 表2 -->笛卡儿积
2.内连接
select * from 表1 inner join 表2 -->笛卡儿积
select * from 表1 join 表2 -->笛卡儿积
select * from 表1 inner join 表2 on 表1.字段=表2.字段
select * from 表1 join 表2 on 表1.字段=表2.字段
select * from 表1 join 表2 where 表1.字段=表2.字段 -->效率没on高
3.外连接
select * from 表1 left join 表2 on 表1.字段 = 表2.字段 -->以左表为主
select * from 表1 right join 表2 on 表1.字段 = 表2.字段 -->以右表为主
select * from 表1 left join 表2 [using(表1和表2相同的字段名)]
select * from 表1 right join 表2 [using(表1和表2相同的字段名)]
4.自然连接(两个表都必须有相同的字段名)
自然内链接
select * from 表1 natural join 表2
自然外链接
select * from 表1 natural left join 表2
select * from 表1 natural right join 表2
二、外键
子表:外键指向的表
父表:拥有外键的表
1.创建外键
create table 表名 (字段 数据类型,字段2 数据类型,foreign key(外键字段) references 父表(主键))
2.添加外键
alter table 表名 add [constraint 外键名字] primary key(外键字段) references 父表(主键)
3.删除外键
alter table 表名 drop primary key 外键名字
4.外键约束模式:
district:严格模式(默认),父表不能删除或更新一个已经被子标数据引用的记录;
cascade:级联模式,父表的操作,对应着子标关联的数据也跟着被删除;
set null:置空模式,父表的操作之后,子表对应的数据(外键字段)被置空
foreign key(外键字段) references 父表(主键) [on delete 模式 on update 模式]