首页 > 解决方案 > SQL | 如果存在另一个等于 (b,c) 的元组,则列出所有元组 (a, b, c)

问题描述

我有三个表,其中粗体属性是主键

resturant_ID,  name,       ...
1,             Macdonalds   
2,             Hubert
3,             Dorsia
...           ...
restaurant_ID, food_ID, ...
1,             1
1,             4
2,             1
2,             7
...            ...
food_ID    food_name
1          Chips
2          Burgers
3          Salmon
...        ...

使用 postgres 我想列出与至少一家其他餐厅共享完全相同的食物的所有餐厅(restaurant_id 和名称 - 每家餐厅 1 行)。

例如,假设

Restaurant_id      name
1                  name1
3                  name3
7                  ...
9                  ...

任何帮助将不胜感激!

谢谢

标签: sqlpostgresqlsetequality

解决方案


使用聚合函数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

请参阅演示


推荐阅读