【SQL进阶教程】之自连接

二、自连接

2.1可重排列、排列、组合

笛卡尔积(直积)
排列:元素按顺序排列
组合:无序排列
自连接:连接相同的表
等值连接:使用等号=
非等值连接:使用< >或者<或>

#可重排列
select P1.name as name_1,P2.name as name_2
from Products P1,Products P2

#排列(去掉相同元素构成的对,即(苹果,苹果)对
select P1.name as name_1,P2.name as name_2
from Products P1,Products P2
where P1.name<>P2.name

#组合,[去重(苹果,香蕉) (香蕉,苹果)]
select P1.name as name_1,P2.name as name_2
from Products P1, Products P2
where P1.name>P2.name

2.2 删除重复行

#使用非等值连接
delete from Products P1
where exists(select * from Products P2 where P1.name=P2.name 
									and P1.price=P2.price
									and P1.rowid<P2.rowid)
#使用极值函数
delete from Products P1
where rowid<(select max(P2.rowid)
			from Products P2 
			where P1.name=P2.name
			and P1.price=P2.price)

2.3查找局部不一致的列

#是一家人但是住址不同
select distinct A1.name,A1.address
from Addresses A1, Addresses A2
where A1.family_id=A2.family_id
and A1.address<> A2.address

排序

select P1.name,P1.price,(select count(P2.price) 
						from Products P2
						where P2.price>P1.price)+1 as rank_1
from Products P1
order by rank_1

你可能感兴趣的:(sql,数据库,database)