MySQL:4个表"has-many-through"加入? [英] MySQL: 4 Table "has-many-through" Join?
问题描述
比方说,我有以下4个表(例如,为了方便起见):所有者,卡车,盒子,苹果.
Let's say I have the following 4 tables (for examples' sake): Owners, Trucks, Boxes, Apples.
一个所有者可以有很多卡车,一辆卡车可以有很多盒子,一个盒子可以有很多苹果.
An owner can have many trucks, a truck can have many boxes and a box can have many apples.
所有者有一个ID.卡车有一个ID和owner_id.盒子有一个id和truck_id.苹果有一个id和box_id.
Owners have an id. Trucks have an id and owner_id. Boxes have an id and truck_id. Apples have an id and box_id.
比方说,我想让所有ID为34的所有者拥有"苹果.因此,我想让所有者34拥有的卡车中的盒子中的所有苹果都拥有.
Let's say I want to get all the apples "owned" by an owner with id = 34. So I want to get all the apples that are in boxes that are in trucks that owner 34 owns.
如果您将拥有4个表,则每个表仅引用其直接父"表,则将具有层次结构".在满足其他3个表的条件的同时,如何快速筛选框?
There is a "hierarchy" if you will of 4 tables that each only has reference to its direct "parent". How can I quickly filter boxes while satisfying conditions across the other 3 tables?
我希望这有些道理.
谢谢.
推荐答案
select a.*
from Trucks t
inner join Boxes b on t.id = b.truck_id
inner join Apples a on b.id = a.box_id
where t.owner_id = 34
这篇关于MySQL:4个表"has-many-through"加入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!