-2

Possible Duplicate:
How can an SQL query return data from multiple tables

I have 3 table

Attribute

attr_id | attr_name 
1       | oval<
2       | white

Product

product_id|product_name 
1         | amazonite 
2         | agate

attr_detail

attr_detail_id | attr_id | product_id
1              | 1       | 1
2              | 2       | 1
3              | 1       | 2
4              | 2       | 2

Now I want product those are oval shape and white color. How to use join.

1
  • 1
    Search the web for MySQL JOIN. Commented Dec 29, 2012 at 17:46

1 Answer 1

1

Try this:

SELECT DISTINCT
  p.product_id, 
  p.product_name 
FROM Product p 
INNER JOIN attr_detail ad ON p.product_id = ad.product_Id
INNER JOIN Attribute a    ON a.attr_id = ad.attr_id
WHERE a.attr_id IN(1, 2);

SQL Fiddle Demo

This will give you:

| PRODUCT_ID |           PRODUCT_NAME |
---------------------------------------
|          1 |              amazonite |
|          2 |                  agate |
|          3 | Product has only white |

Note that: This will give you the products names that have either the white or oval shapes. However, if you are looking for only those products that has both the two shapes, you have to modify your query like so:

SELECT DISTINCT
  p.product_id, 
  p.product_name 
FROM Product p 
INNER JOIN
(
  SELECT product_id
  FROM attr_detail
  WHERE attr_id IN(1, 2)
  GROUP BY product_id
  HAVING COUNT(DISTINCT attr_id) = 2
) ad ON p.product_id = ad.product_Id;

Updated SQL Fiddle Demo

This will give you:

| PRODUCT_ID | PRODUCT_NAME |
-----------------------------
|          1 |    amazonite |
|          2 |        agate |

Please read more about JOINs. Here you can find a useful information about this:

For what I did in the second query:

  SELECT product_id
  FROM attr_detail
  WHERE attr_id IN(1, 2)
  GROUP BY product_id
  HAVING COUNT(DISTINCT attr_id) = 2

This is called Relational Division.

Sign up to request clarification or add additional context in comments.

5 Comments

In your case it is giving all three products but i want product those have oval and white.
Thank u so much @mahmoud. You explain very well this to me now i understand what i was missing.
@abhi - You're welcome any time. See my edit for more explanation :).
First time i got so detailed answer of my question.Thanks again @mahmoud for explaining joins to me.
Sure, i am reading all..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.