这是 SQL Server 语法,因为我没有 MySql 或 PostGresSQL,但应该给你这个想法:
with branches as (
select * from ( values
('Perth',1),
('Toronto',1), ('Toronto',2), ('Toronto',3),
('Hamilton',2), ('Hamilton',3)
) branches(City, Branch_Type)
)
select distinct
City
from branches
except
select distinct
b.City
from branches t
cross join branches b
left join branches b2 on b2.Branch_Type = t.Branch_Type and b2.City = b.City
where b2.Branch_Type is null
我已将其缩减到最低限度以演示必要的设置操作。
查询的上半部分返回所有三个城市;下半场只回归汉密尔顿和珀斯;这样整个查询只返回多伦多。
30 年来我没有使用过关系代数或关系微积分,但用这些方言表达上述查询只是一个翻译练习。
更新 - 对于 MySQL:
with branches as (
select * from ( values
('Perth',1),
('Toronto',1), ('Toronto',2), ('Toronto',3),
('Hamilton',2), ('Hamilton',3)
) branches(City, Branch_Type)
)
select distinct
City
from branches
where City not in (
select distinct
b.City
from branches t
cross join branches b
left join branches b2 on b2.Branch_Type = t.Branch_Type and b2.City = b.City
where b2.Branch_Type is null
)
由于子查询位于 WHERE 子句而不是 FROM 子句中,因此这是合法的。它可以表示为左连接,但我认为这会将子查询移动到 FROM 子句中。