sql - SQL | 如果存在另一个等于 (b,c) 的元组,则列出所有元组 (a, b, c)
问题描述
我有三个表,其中粗体属性是主键
- 餐厅(餐厅 ID,名称,...)
resturant_ID, name, ...
1, Macdonalds
2, Hubert
3, Dorsia
... ...
- 标识符( restaurant_ID , food_ID )
restaurant_ID, food_ID, ...
1, 1
1, 4
2, 1
2, 7
... ...
- 食物(食物ID,名称,...)
food_ID food_name
1 Chips
2 Burgers
3 Salmon
... ...
使用 postgres 我想列出与至少一家其他餐厅共享完全相同的食物的所有餐厅(restaurant_id 和名称 - 每家餐厅 1 行)。
例如,假设
- ID 为“1”的餐厅仅关联 food_id 的 1 和 4 ,如图所示
Identifier
- ID 为“3”的餐厅仅关联 food_id 的 4 和 1 ,如图所示
Identifier
- ID 为“7”的餐厅只关联了 food_id 的 6 ,如图所示
Identifier
- ID 为“9”的餐厅仅关联 food_id 的 6 ,如图所示
Identifier
- 然后输出
Restaurant_id name
1 name1
3 name3
7 ...
9 ...
任何帮助将不胜感激!
谢谢
解决方案
使用聚合函数string_agg()
获取每家餐厅的完整食物列表:
with cte as (
select restaurant_ID,
string_agg(food_ID::varchar(10),',' order by food_ID) foods
from identifier
group by restaurant_ID
)
select r.*
from Restaurants r inner join cte c
on c.restaurant_ID = r.restaurant_ID
where exists (select 1 from cte where restaurant_ID <> c.restaurant_ID and foods = c.foods)
但我更愿意根据匹配的食物对餐厅进行分组:
with cte as (
select restaurant_ID,
string_agg(food_ID::varchar(10),',' order by food_ID) foods
from identifier
group by restaurant_ID
)
select string_agg(r.name, ',') restaurants
from Restaurants r inner join cte c
on c.restaurant_ID = r.restaurant_ID
group by foods
having count(*) > 1
请参阅演示。
推荐阅读
- python-3.x - (openpyxl) FileNotFoundError: [Errno 2] 没有这样的文件或目录
- android - RxJava:嵌套的观察者
- graphql - 如何在 GatsyJS 的 pageQuery 中执行顺序查询?
- ansible - ansible-playbook with_flattened 迁移到循环
- scala - 如何使用scala读取tcp流
- sql - 根据列值动态获取列名
- http - 从服务器的角度来看,413 Payload Too Large 毫无意义吗?
- javascript - 有没有办法操纵加载到外部 iframe 中的 wordpress 帖子样式?
- php - PHP在多维数组中添加值
- excel - 递增不给出预期结果的语法