sql select in relation many-to-many not works as expected
i have the following tables in relation many-to-many:
table product:
prd_cod (pk)
cat_cod (fk)
prd_nome
table description_characteristic:
prd_cod(fk)
id_characteristic(fk)
description
table characteristic:
id_characteristic(pk)
name
we suppose that the cat_cod will be 1, so i want to show all the products that have the category code equals 1,that will be provided dynamically in php for parameter …
I have done this select below to solve my problem:
select p.prd_cod,p.prd_name,c.name_characteristic,dc.description
from product p,description_characteristic dc, characteristic c
where p.prd_cod = dc.prd_cod and
dc.id_ccharacteristic = c.id_characteristic and
p.cat_cod = 1
but the data were shown this way:
Prd_cod Prd_name name_characteristic descript
1 pen Color pink
1 Pen manufacturer kingston
1 Pen type brush
1 Pen weight 0.020
I want to show the result this way:
Prd_cod Prd_name name_characteristic descript name_characteristic descript
1 pen Color pink type brush
2 Pen-drive manufacturer kingston weight 0.020
I would like to show all the characteristics of the same product, and not just two as above…
I can not do a select to solve this
please i need help
Thank you all
As stated by Tom H., your database layout may generally be a bad idea and you might reconsider it. That said, there is no really clean solution producing the mysql result set you want. But you might use something crazy with GROUP_CONCAT like this, reproducing the real data with some PHP-side postprocessing:
This should return something like
this result set should be post-processed like this:
I would not call this a robust solution, though – for example, commas in your values screw things up. If you want to avoid madness like this, you’ll have to postprocess the result you already get.
But if you want to show some mad sql aggregation skills (and you seem to be interested as you’ve chosen this database layout), this one is for you.