开发者

mysql - query three tables

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开发者_Go百科 third table that relate to it?

Sorry I am new to mySQL.


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'


yes

SELECT t3.* 
  FROM t1, t2, t3
  WHERE t1.id = t2.id
    AND t2.otherid = t3.id
    AND t1.id = XXXX


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'


Use the JOIN command to link your tables to oneantother.

Additionally I'd recommend this tutorial by Keith Brown.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜