如何在一列中加入多个不同的行

How to join multiple distinct rows in one column

我有 3 table

餐馆table:

restaurant_id restaurant_name
1 Burger King
2 Coffee shop

食品table:

food_id food_title category_id restaurant_id
1 Burger with cheese 1 1
2 Beef Burger 2 1
3 Beef Burger with cheese 2 1
4 Iced Coffee 3 2
5 Dark Coffee 3 2
5 Green Tea 4 2

类别table:

category_id category_title
1 Normal Burger
2 Beef Burger
3 Coffee
4 Tea

我正在寻找的输出:

restaurant_id restaurant_name categories_list
1 Burger King [{category_id: 1, category_title: 'Normal Burger'}, {category_id: 2, category_title: 'Beef Burger'}]
2 Coffee shop [{category_id: 3, category_title: 'Coffee'}, {category_id: 4, category_title: 'Tea'}]

尝试:

    select restaurant_id,restaurant_name,concat('[',group_concat(my_col),']') as tot_result
from ( select r.restaurant_id,r.restaurant_name,concat('{category_id: ', c.category_id," category_title: '",c.category_title ,"'}") as my_col
       from Restaurants r
       inner join Foods f on r.restaurant_id=f.restaurant_id
       inner join Categories c on c.category_id=f.category_id
       group by r.restaurant_id,r.restaurant_name,my_col
     ) as t1
group by restaurant_id,restaurant_name;

结果:

restaurant_id   restaurant_name   tot_result
    1            Burger King    [{category_id: 1 category_title: 'Normal Burger'},{category_id: 2 category_title: 'Beef Burger'}]
    2            Coffee shop    [{category_id: 3 category_title: 'Coffee'},{category_id: 4 category_title: 'Tea'}]

Demo

通过 LEFT 加入 RestaurantsFoodsCategories 并按餐厅分组。
然后使用 JSON_ARRAYAGG() 聚合函数获取列表:

SELECT r.restaurant_id, r.restaurant_name,
       JSON_ARRAYAGG(JSON_OBJECT('category_id', c.category_id, 'category_title', c.category_title)) categories_list
FROM Restaurants r
LEFT JOIN (SELECT DISTINCT category_id, restaurant_id FROM Foods) f ON f.restaurant_id = r.restaurant_id
LEFT JOIN Categories c ON c.category_id = f.category_id
GROUP BY r.restaurant_id, r.restaurant_name;

我在 table Foods 中使用 SELECT DISTINCT ... 因为我在您的预期结果中看到您希望每个列表中的不同类别。

参见demo