i got three tables
CATS
id name
------------------------------
1 category1
2 category2
3 category3
4 category4
PRODUCT
id name
------------------------------
1 product1
2 product2
ZW-CAT-PRODUCT
id_cats id_product
------------------------------
1 1
3 1
4 2
now i want to get my products and their categories
product1 => category1,category3
product2 => category4
is there a way to get this array (or object or something) with one mysql query?
i tried a bit with JOINS, but it seems thats this is not exactly what i need, or?
currently i’m using 3 querys (i think thats too much).
any suggestions?
edit
and on the other way, what if i want to get ALL products of a specific category?
can this also be done in one query?
You can use GROUP_CONCAT to get a separated list in your results.
So basically, this first does some joins to get all the data. If you were to replace the
GROUP_CONCATline with justc.name, you would see a row for each product_id/category pair. TheGROUP BYtells it to group results based on product ID, and thenGROUP_CONCAT(c.name..)is telling to it take all the differentc.namevalues that occur in a group (so for each product ID, since you’re grouping by product ID) and concatenate those values into one string, using,as the separator.So to get all products for a each category in the same style, it would be like this,
EDIT: To get just the product rows for a particular category (as requested in comment), it’s this.