1,右连接和子连接的联合使用
例一:某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
利用右连接,找到orders中id存在的Customers
select c.Id from Customers c inner join Orders o on o.CustomerId = c.Id
再使用子链接找到id不在上表中的Name
select Customers.name as Customers from Customers where Customers.Id not in (select c.Id from Customers c inner join Orders o on o.CustomerId = c.Id);
2,删除和自连接的联合使用
首先使用自连接找到要删除的信息
select p1.* from Person p1 inner join Person p2 where p1.Email = p2.Email and p1.id > p2.id
然后将select替换为delete
delete p1.* from Person p1 inner join Person p2 where p1.Email = p2.Email and p1.id > p2.id
3,排序和取到奇数id的联合使用
您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列
elect * from cinema c where mod(c.id,2)= 1 and description != 'boring' order by rating desc
desc 从大到小
asc 从小到大
where mod(r.id,2) = 0; 获取偶数id
where mod(r.id,2) = 1; 获取奇数id
where比较运算符
select w.name, w.population, w.area from World w where area > 3000000 or population > 25000000
外键约束
什么是外键约束:
外键 foreign key: 对关系字段进行约束, 当为关系字段填写值时, 会到关联的表中查询此值是否存在, 如果存在则填写成功, 如果不存在则填写失败并抛出异常.
外键约束的作用:
对外键字段的值进行更新和插入时会和引用表中字段的数据进行验证,数据如果不合法则更新和插入会失败,保证数据的有效性
外键约束的使用:
添加外键约束: alter table 从表 add foreign key(外键字段) references 主表(主键字段);
-- 创建学校表
create table school(
id int not null primary key auto_increment,
name varchar(10)
);
-- 创建老师表
create table teacher(
id int not null primary key auto_increment,
name varchar(10),
s_id int not null,
foreign key(s_id) references school(id)
);