I have a fields table like this:
product_id |aid |value|
------------|-------|-----|
789 |6 |1 |
789 |6 |3 | -->aid = 6 , value = 3
789 | 8| 8| -->rows that i want with aid 8
789 | 8| 11| -->rows that i want with aid 8
789 | 8| 82| -->rows that i want with aid 8
------------|-------|-----|
790 |6 |2 |
790 |6 |3 | -->aid = 6 , value = 3
790 |6 |4 |
790 | 8| 8| -->rows that i want with aid 8
790 | 8| 16| -->rows that i want with aid 8
------------|-------|-----|
791 |6 |7 |
791 |8 |13 |
------------|-------|-----|
I want all rows with aid = 8 for specific products that have pair of (aid = 6 AND value = 3)
what i did:
First i select distinct product_ids having aid = 6
and value = 3
.
Then i select all rows with aid where product_ids are IN previous select query.
here is my query which take about 1 second.
SELECT DISTINCT `value` FROM `fields`
WHERE aid = 8 AND product_id IN
(
SELECT DISTINCT `fields`.product_id FROM `fields`
WHERE aid = 6 AND `value` = 3
)
the value result is 8,11,82,16
is there a more optimized way to do this?