I have a query that finds categories by product id. Note: Some products can have multiple categories. My current query returns the same ids for different categories
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 | category_name |
---|---|
100 | storage |
100 | SSD |
100 | HDD |
200 | storage |
200 | SSD |
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.
Desired output:
product_id | category_name | category_name 2 | category_name 3 |
---|---|---|---|
100 | storage | SSD | HDD |
200 | storage | SSD | HDD |
The columns of an SQL query must be fixed at the time the query is parsed. A query cannot append more columns as it discovers the data during execution.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.