[英]Merge rows with same id but different values into single row per id
I have a query that finds categories by product id.我有一个按产品 ID 查找类别的查询。 Note: Some products can have multiple categories.注意:某些产品可以有多个类别。 My current query returns the same ids for different categories我当前的查询为不同的类别返回相同的 id
SELECT
oc_product.product_id,
oc_category_description.name
FROM
oc_product
LEFT JOIN oc_product_to_category ON oc_product.product_id = oc_product_to_category.product_id
LEFT JOIN oc_category_description ON oc_product_to_category.category_id = oc_category_description.category_id;
Result:结果:
product_id product_id | category_name分类名称 |
---|---|
100 100 | storage贮存 |
100 100 | SSD固态硬盘 |
100 100 | HDD硬盘 |
200 200 | storage贮存 |
200 200 | SSD固态硬盘 |
200 200 | HDD硬盘 |
I would like to merge the rows with the same product_id and add each category_name as an extra column to the left.我想合并具有相同 product_id 的行,并将每个 category_name 作为额外的列添加到左侧。
Desired output:所需的 output:
product_id product_id | category_name分类名称 | category_name 2类别名称 2 | category_name 3类别名称 3 |
---|---|---|---|
100 100 | storage贮存 | SSD固态硬盘 | HDD硬盘 |
200 200 | storage贮存 | SSD固态硬盘 | HDD硬盘 |
The columns of an SQL query must be fixed at the time the query is parsed. SQL 查询的列必须在解析查询时固定。 A query cannot append more columns as it discovers the data during execution.查询不能 append 更多列,因为它在执行期间发现数据。
You could use pivot-table techniques, but only if you know how many columns you need for the number of categories per product.您可以使用数据透视表技术,但前提是您知道每个产品的类别数量需要多少列。
I suggest you fetch the results in rows as in your first example, and then write code in your client application to format it into columns.我建议您像在第一个示例中那样按行获取结果,然后在客户端应用程序中编写代码以将其格式化为列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.