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
You have to join again to the other tables. You’ll need to alias the tables to distinguish them apart:
You could put the test for value in the
WHEREclause, 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 JOINandJOINare identical in meaning (INNERis implied)