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.
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:
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:
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:
What is a better way to write a query for a distant relationship like this?
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. 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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.