简体   繁体   English

MySQL:4表“has-many-through”加入?

[英]MySQL: 4 Table “has-many-through” Join?

Let's say I have the following 4 tables (for examples' sake): Owners, Trucks, Boxes, Apples. 假设我有以下4个表(例如'缘故):所有者,卡车,盒子,苹果。

An owner can have many trucks, a truck can have many boxes and a box can have many apples. 拥有者可以有很多卡车,卡车可以有很多箱子,一个箱子可以有很多苹果。

Owners have an id. 业主有身份证。 Trucks have an id and owner_id. 卡车有一个id和owner_id。 Boxes have an id and truck_id. 盒子有id和truck_id。 Apples have an id and box_id. 苹果有一个id和box_id。

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. 假设我想让所有拥有id = 34的拥有者“拥有”所有苹果。所以我想得到所有拥有34所拥有卡车的盒子里的苹果。

There is a "hierarchy" if you will of 4 tables that each only has reference to its direct "parent". 如果您将使用4个表,每个表只引用其直接“父”,则存在“层次结构”。 How can I quickly filter boxes while satisfying conditions across the other 3 tables? 如何在满足其他3个表格的条件的同时快速过滤盒子?

I hope that made sense somewhat. 我希望这有点意义。

Thanks. 谢谢。

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

You just start at the "top" (owners) and keep joining until you get where you want: 你只需从“顶层”(业主)开始并继续加入,直到你到达你想要的地方:

SELECT a.*
FROM Owners o
INNER JOIN Trucks t ON t.owner_id = o.id
INNER JOIN Boxes b on b.truck_id = t.id
INNER JOIN Apples a on a.box_id = b.id
WHERE o.id = ?

If queries like that are needed often and you are working with very large data sets, sometimes it makes sense to denormalize the data a bit as well. 如果经常需要这样的查询并且您正在使用非常大的数据集,那么有时对数据进行非规范化也是有意义的。 For example by adding the owner_id to the apples table. 例如,将owner_id添加到apples表中。 It makes inserting/updating the data a bit more difficult, but can make queries easier. 它使插入/更新数据更加困难,但可以使查询更容易。

    SELECT a.*
      FROM Apples a
INNER JOIN Boxes b ON b.id = a.box_id
INNER JOIN Trucks t ON t.id = b.truck_id
INNER JOIN Owners o ON o.id = t.owner_id
     WHERE o.id = 34

You can simplify this somewhat by leaving out the join to owners and just selecting where t.owner_id = 34 if you don't need any information about the owner later. 如果您以后不需要任何有关所有者的信息,您可以通过省略对所有者的联接并仅选择t.owner_id = 34的位置来简化此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM