MySQL:4 个表“有很多通过”加入?
假设我有以下 4 个表(为了举例):车主、卡车、盒子、苹果。
一个业主可以拥有许多卡车,一辆卡车可以有许多箱子,一个箱子可以有许多苹果。
业主有一个ID。卡车有 id 和 Owner_id。盒子有一个 id 和 Truck_id。苹果有一个 id 和 box_id。
假设我想要获取 id = 34 的所有者“拥有”的所有苹果。因此,我想要获取所有者 34 拥有的卡车内的盒子中的所有苹果。
如果您愿意的话,有一个“层次结构”,其中有 4 个表,每个表仅引用其直接“父级”。如何快速过滤框,同时满足其他 3 个表的条件?
我希望这是有道理的。
谢谢。
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.
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.
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.
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?
I hope that made sense somewhat.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需从“顶部”(所有者)开始,然后继续加入,直到到达您想要的位置:
如果经常需要这样的查询,并且您正在处理非常大的数据集,有时对数据进行非规范化也是有意义的。例如,将 Owner_id 添加到 apples 表中。它使插入/更新数据变得更加困难,但可以使查询更容易。
You just start at the "top" (owners) and keep joining until you get where you want:
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. It makes inserting/updating the data a bit more difficult, but can make queries easier.
如果稍后不需要有关所有者的任何信息,您可以通过省略对所有者的连接并仅选择 t.owner_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.