简体   繁体   English

查询遥远的关系

[英]Querying for distant relations

I'm working on modeling some relational data in an app. 我正在为应用程序中的一些关系数据建模。 I'm wondering mostly about how to deal with distant relations in SQL, though for context it's a Ruby app and I'm using Sequel as an ORM. 我主要想知道如何处理SQL中的远距离关系,尽管就上下文而言,这是一个Ruby应用程序,而我正在使用Sequel作为ORM。

One example relationship looks like this: 一个示例关系如下所示:

alphas one-to-many bravos
bravos many-to-one charlies
charlies one-to-many deltas
deltas one-to-many echoes

So, using the ORM and doing the work in Ruby I might naively query for all Echoes related to an Alpha like so: 因此,使用ORM并在Ruby中进行工作,我可能会天真地查询与Alpha相关的所有Echoes,如下所示:

a = Alpha.where id: 1
echoes = []
a.bravos.each do |bravo|
  bravo.charlie.deltas.each do |delta|
    echoes << delta.echoes
  end
end
echoes.flatten

This works but fails to take advantage of the database and rather does most of the work in the application layer. 此方法有效,但无法利用数据库,而是在应用程序层中完成了大部分工作。 Expressing the same idea in ugly psuedo-sql subqueries it would look like: 在丑陋的psuedo-sql子查询中表达相同的想法看起来像:

SELECT * FROM echoes WHERE delta_id IN
  SELECT delta_id FROM charlies WHERE charlie_id IN
    SELECT charlie_id FROM bravos WHERE bravo_id IN
      SELECT id FROM bravos WHERE alpha_id = 1

This is essentially the same brute force approach, it seems like there must be a better way. 这本质上是相同的蛮力方法,似乎必须有更好的方法。

So my question is: 所以我的问题是:

  1. What is a better way to write a query for a distant relationship like this? 像这样的遥远关系写查询的更好方法是什么?

  2. Is there a change to the schema design that should be made to represent this kind of distant relation? 对表示这种遥远关系的模式设计是否进行了更改?

It occurs to me that I could create an alpha_id column on echoes and use this to query directly, I then would rely on the application to always update that column if the intermediate relations change. 在我看来,我可以在echoes上创建一个alpha_id列,并使用它直接查询,然后,如果中间关系发生变化,我将依靠应用程序始终更新该列。 That seems to me like a bad idea, but it would certainly make for more efficient queries in this case. 在我看来,这是一个坏主意,但是在这种情况下,它肯定会使查询效率更高。

I'd love to hear from some SQL pros, what do you do when you have distantly related data that you need to query frequently? 我很想听听一些SQL专家的意见,当您需要经常查询的遥远相关数据时,您会怎么做?

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

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