我有3张桌子
表1: PRODUCT_ID 名称 描述
表2: CATEGORY_ID 名称 描述
表3: PRODUCT_ID CATEGORY_ID
我尝试创建一个选择包含以下数据的表的查询:product_name,product_description,product_category
事情是每行应包含多个product_category,但查询只返回一个。
以下是查询,如果您能告诉我哪些部分不正确
SELECT table1.name AS product_name,
table1.description AS product_description,
table2.name AS product_category
FROM table1 INNER JOIN
table3
ON table3.product_id = table1.product_id INNER JOIN
table2
ON table2.category_id = table3.category_id;
我得到的结果是:
product_name - product_description - product_category
NAME 1 - Description 1 - Category 1
NAME 2 - Description 2 - Category 2
我的目标是这样:
product_name - product_description - product_category
NAME 1 - Description 1 - Category 1
Category 2
Category 5
NAME 2 - Description 2 - Category 7
Category 2
Category 1
答案 0 :(得分:1)
如果您想要在一行中使用多个产品类别,请考虑"聚合":
Rails 4
答案 1 :(得分:0)
我已经找到答案所有功劳都归功于@Gordon Linoff,因为我需要做的就是将product_id添加到分组中
以下是查询:
SELECT t1.name AS product_name,
t1.description AS product_description,
GROUP_CONCAT(t2.name) AS product_category
FROM table1 t1 INNER JOIN
table3 t3
ON t3.product_id = t1.product_id INNER JOIN
table2 t2
ON t2.category_id = t3.category_id
GROUP BY t1.product_id, t1.name, t1.description;
谢谢!