views:

83

answers:

6

I have a relational database with three tables. The first containts id's that relate to the second. The second contains id's that relate to the third. The third contains the results I am after.

Is it possible with a single query to query an id in the first table which gives all results from the third table that relate to it?

Sorry I am new to mySQL.

+5  A: 

Mysql Join

Try this

select * from table1 t1
join table2 t2 on t1.t2ref = t2.id
join table3 t3 on t2.t3ref = t3.id

Add a where clause to search for certain rows in table1

where t1.field = 'value'
Peter Lindqvist
+1  A: 

Use the JOIN command to link your tables to oneantother.

Additionally I'd recommend this tutorial by Keith Brown.

KB22
A: 

You want to do a join. There is a lot of tutorials about this and various ways of doing it.

marcgg
+2  A: 

yes

SELECT t3.* 
  FROM t1, t2, t3
  WHERE t1.id = t2.id
    AND t2.otherid = t3.id
    AND t1.id = XXXX
rikh
Thank you... I tried it and it worked perfectly... I also tried Peter Lindqvist's approach (using joins). I heard JOIN's are expensive. Your solution came out at 0.0004 second as apposed to 0.0005 seconds. At the moment I hardly have any data though. Which is likely to be more efficient?
Mark
the mysql query optimizer will transform this query also into a join
knittl
i think that the difference you experience is actually not significant. If you get slow queries you need to examine your index structure. Joins with 3 tables and the proper indexing will normally not become slow.
Peter Lindqvist
+2  A: 

you want to use a join:

   SELECT `t3`.`id`
     FROM `table3` `t3`
LEFT JOIN `table2` `t2`
       ON `t3`.`foreign_id` = `t2`.`id`
LEFT JOIN `table1` `t1`
       ON `t2`.`foreign_id` = `t1`.`id`
    WHERE `t1`.`id` = 'some_id'
knittl
A: 

the type of join needed depends on if corresponding rows exist in the other tables.... give more details

CheeseConQueso