2

I have a table that looks like this:

| id   | product | prod_id |
| 1001 | Item 1  | P1001   |
| 1002 | Item 2  | P1001   |
| 1003 | Item 3  | P1003   |

My desired output is:

| id   | prod_id        |
| 1001 | Item 1, Item 2 |
| 1003 | Item 3         |

As you can see, Item 1 and 2 has the same prod_id.

This is what I tried:

select id, prod_id from table_name where prod_id = product;

Basically what I tried was to merge all the products with the same prod_id and then just display them as id & prod_id.

I am new to mySQL and would love some feedback on how I can do this. I am not sure if my logic is correct in trying to fix the issue.

1 Answer 1

3

You can try to use aggregate function MIN with GROUP_CONCAT

Schema (MySQL v5.7)

CREATE TABLE T(
  id int,
  product varchar(50),
  prod_id varchar(50)
);


INSERT INTO T VALUES (1001,'Item 1','P1001');
INSERT INTO T VALUES (1002,'Item 2','P1001');
INSERT INTO T VALUES (1003,'Item 3','P1003');

Query #1

SELECT MIN(id) id,GROUP_CONCAT(product) prod_id        
FROM T
GROUP BY prod_id;

| id   | prod_id       |
| ---- | ------------- |
| 1001 | Item 1,Item 2 |
| 1003 | Item 3        |

View on DB Fiddle

3
  • and in case you want to incorporate the id into the group you can extend the GROUP CONCAT to GROUP_CONCAT(CONCAT(product, " (", id, "("))
    – Moseleyi
    Nov 8, 2018 at 2:26
  • D-Shih, this is the perfect answer! Thank you for teaching me about the GROUP_CONCAT. I'll go study on it. And yes, I tried what you posted and it works exactly the way I need it to be. I'll mark your answer correct in 2 mins when it allows me to. Thank you D-Shih.
    – Gosi
    Nov 8, 2018 at 2:28
  • @gosi123 No problem glad to help you :)
    – D-Shih
    Nov 8, 2018 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.