0

My purchaseproduct table

+------------+------------+
| productids | quantities |
+------------+------------+
| 1,3,4,5    | 1,1,1,1    |
| 2,3,4,5    | 1,1,1,1    |
+------------+------------+

My product table

 productsid | productsname                 |
+------------+-----------------------------+
|          1 | Phone                       |
|          2 | Laptop                      |
|          3 | Charger                     |
|          4 | Earphone                    |
|          5 | Camera                      |

I want to get product name based on productids in purchaseproduct table

Like below Out put is needed

Phone,Charger,Earphone,Camera (In row one)
Laptop,Charger,Earphone,Camera (In row two)

I tried this below statement and many other

select group_concat(p.productsname) from purchaseproducts as pp join products as p on find_in_set(p.productsid,pp.productids);

But the output I get is

 Phone,Charger,Earphone,Camera,Laptop,Charger,Earphone,Camera (All in one row)

How can I achieve the output I need?

3
  • 2
    You know why you are asking this question? Because you overlooked the database design. Storing comma separated values is just too bad! Is storing a delimited list in a database column really that bad? YES Commented Jul 13, 2016 at 10:07
  • @1000111-Requirement is such that.. :( Commented Jul 13, 2016 at 10:08
  • Change the requirement. Commented Jul 13, 2016 at 10:10

1 Answer 1

1

You can simply use DISTINCT inside the GROUP_CONCAT :

select pp.productsid , group_concat(DISTINCT p.productsname)
from purchaseproducts pp 
join products p 
 on find_in_set(p.productsid,pp.productids);
GROUP BY pp.productsid
Sign up to request clarification or add additional context in comments.

8 Comments

using distinct is not working it also prints only one row but disting out put
Need to use GROUP BY. By the way, isn't there any PK in purchaseproduct table? @RajaDhasan
Thanks working.. I used group by with a unique PK in my table
If there were another row having productsid = 1,4,3,5 then you would get three rows. Although you would expect to get 2 rows. That's why CSV is bad @RajaDhasan
@1000111 How do you know he expects to get 2 in this case? And yea, in general I highly agree.. change the DB design!
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.