tags:

views:

29

answers:

1

I have two tables, products and product_tags.

products table;

product_id int
name varchar
description text
price decimal(12,2)
status enum
sale int
hit int
date_add datatime
date_update datetime

product_tags table;

tag_id int
product_id int
tag varchar

where the product_tags table has a one to many relation with products, for example:

tag_id | product_id | tag
1       1             tag1
2       1             tag2
3       1             tag3

I want to pull data from a single query. (product and product tags).

+2  A: 

Use something like this:

SELECT *
  FROM products p
 INNER JOIN product_tags pt
    ON (p.product_id = pt.product_id)

If you want to fetch all the products regardless of whether they have a tag or not, then use an OUTER JOIN.

SELECT *
  FROM products p
  LEFT OUTER JOIN product_tags pt
    ON (p.product_id = pt.product_id)

If you are trying to combine all of the tags for each product into a single comma-separated list then something like this might work in mysql:

SELECT p.product_id, GROUP_CONCAT(pt.tag SEPARATOR ',')
  FROM products p
  LEFT OUTER JOIN product_tags pt
    ON (p.product_id = pt.product_id)
 GROUP BY p.product_id;

For further documentation of GROUP_CONCAT, see the MySQL Reference Manual

Tom
tom thank for your answer. But I tried this.this query retruns more rows. if product has there tags. this query returns three rows.
alioygur
yes, if you are selecting data for products AND tags you will get a row for each combination of product and tag. If a product has 3 tags then there will be three rows for that product, one for each tag.What exactly do you want? Do you want one row for each product with a single column containing a concatenation of all its tags? That sounds a little strange.
Tom
yes i want only result with tags. I think this is not possible. I need to do two separate queries for this is.like this;$query_product_data = mysql_query("SELECT * FROM products where product_id = '1'");$query_product_tags_data = mysql_query("SELECT * FROM product_tags WHERE product_id = '1'");this is best way ?
alioygur
It is possible in mysql. I've edited my answer to include a solution.
Tom
oh thank you so much i wanted.
alioygur
No problem. Glad to help.
Tom