0

我有 3 张桌子:

businesses ( id, name )
categories ( id, name )
business_categories ( business_id, category_id )

第三张桌子是多对多的,PRIMARY KEY那对有一张。

我正在尝试创建一个类似于以下内容的视图:

business_name    category_names
Pizza Hut        Restaurants, Pizza, Fast Food
Chipotle         Restaurants, Mexican, Fast Food

这是我正在尝试的

SELECT `businesses`.`name`, CONCAT_WS( ',', (
    SELECT `name`
    FROM `categories`
    JOIN `business_categories`
        ON `categories`.`id` = `business_categories`.`category_id`
    WHERE `business_categories`.`business_id` = `businesses`.`id`
) ) 
FROM  `businesses` 
ORDER BY  `businesses`.`id` ASC 

但我收到此错误:

Subquery returns more than 1 row
4

1 回答 1

1

您可以使用GROUP_CONCAT()函数来实现:

SELECT
  businesses.name,
  GROUP_CONCAT(categories.name) AS all_categories
FROM
  businesses
    LEFT JOIN business_categories
      ON businesses.id=business_categories.business_id
    LEFT JOIN categories
      ON business_categories.category_id=categories.id
GROUP BY
  businessess.name
于 2013-09-12T14:30:59.563 回答