Vecta
Vecta

Reputation: 2350

SELECT Statement Refinement

I'm quite a novice when it comes to MySQL and relational databases, but a project I'm working on is requiring me to write some complex SELECT statements and I'm a bit confused at this point. I have three tables that store information about various products. Table1 stores page content for each of the products, table2 stores specific criteria about each product (model, material, color, etc), table3 is a linking table to establish a many-to-many relationship between T1 and T2.

This is what my select statement is giving me:

Array
(
    [name] => color
    [value] => Red
    [title] => Product 1
)
Array
(
    [name] => material
    [value] => Wood
    [title] => Product 1
)

I'm confused on how I could select products that are, for instance, both 'red' and 'wood'—basically have records of each product and their descriptions.

Array
(
    [material] => Wood
    [color] => Red
    [title] => Product 1
)

SELECT Statement:

SELECT table2.name, table3.value, table1.title
FROM table2

INNER JOIN table3
ON table2.id=table3.varid

INNER JOIN table1
ON table1.id=table3.contentid

Upvotes: 2

Views: 54

Answers (1)

Bohemian
Bohemian

Reputation: 425033

You have to join again to the other tables. You'll need to alias the tables to distinguish them apart:

SELECT table2.name, table3.value, table1.title, t3.value, t1.title
FROM table2
JOIN table3 ON table2.id=table3.varid and value = 'Wood'
JOIN table1 ON table1.id=table3.contentid
JOIN table3 t3 ON table2.id=t3.varid and value = 'Red'
JOIN table1 t1 ON t1.id=t3.contentid;

You could put the test for value in the WHERE clause, but this way is more efficient because the predicate is executed as the join is made, rather than afterwards on the entire join result.

Note that INNER JOIN and JOIN are identical in meaning (INNER is implied)

Upvotes: 1

Related Questions