mysql - query three tables

2019-01-20 14:44发布

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条回答
Summer. ? 凉城
2楼-- · 2019-01-20 15:28

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

查看更多
SAY GOODBYE
3楼-- · 2019-01-20 15:32

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'
查看更多
叼着烟拽天下
4楼-- · 2019-01-20 15:40

yes

SELECT t3.* 
  FROM t1, t2, t3
  WHERE t1.id = t2.id
    AND t2.otherid = t3.id
    AND t1.id = XXXX
查看更多
Emotional °昔
5楼-- · 2019-01-20 15:43

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'
查看更多
走好不送
6楼-- · 2019-01-20 15:47

Use the JOIN command to link your tables to oneantother.

Additionally I'd recommend this tutorial by Keith Brown.

查看更多
登录 后发表回答